我正在使用 Ajax BeginForm 进行后处理。传入控制器的值为 null。但是当我使用
SettingViewModel
时,不会出现 null。但我需要使用我的UsersRegister
模型。
剃须刀:
@model GAP_Bakim.ViewModel.SettingViewModel
@using (Ajax.BeginForm("Details", "Setting", new AjaxOptions { HttpMethod = "POST", OnSuccess = "detailSuccess", OnFailure = "detailFailure" }))
{
@Html.AntiForgeryToken()
<div class="input-box mb-3">
<span>Kullanıcı Adı</span>
@Html.TextBoxFor(m => m.UsersDetails.username, new { @class = "form-control details-inputs", id = "detailUsernameInput", required = "required", @readonly = "readonly" })
</div>
<div class="input-box mb-3">
<span>Ad</span>
@Html.TextBoxFor(m => m.UsersDetails.kullaniciAd, new { @class = "form-control details-inputs", id = "detailNameInput", required = "required", maxlength = 25, pattern = "[A-Za-zğüşıöçĞÜŞİÖÇ\u0020]+" })
</div>
控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Details(UsersDetails users)
视图模型:
public class SettingViewModel
{
public Settings Settings { get; set; }
public UsersDetails UsersDetails { get; set; }
}
型号:
public class UsersDetails
{
public string username { get; set; }
public string kullaniciAd { get; set; }
}
TextBoxFor
正在根据模型属性自动生成 name
属性:
m.UsersDetails.username
该属性提供发送到服务器的键/值对中的键。除非另有说明,否则框架假定在后续操作中将使用相同的模型,但此处的情况并非如此。所以得到的名称属性:
name="UsersDetails.username"
与您模型上的属性名称不匹配:
public string username { get; set; }
您可以手动覆盖
name
的 HTML 属性中的 TextBoxFor
属性:
new { name = "username", @class = "form-control details-inputs", id = "detailUsernameInput", required = "required", @readonly = "readonly" }
^-- here
对另一个
TextBoxFor
执行相同的操作,使其生成的 name
属性也与其预期的模型属性相匹配。