我不完全确定最好的方式,但是,我正在寻找“正确”的方式来处理通过ajax提交将动态复杂视图模型发回到视图。我觉得它已经过去了,但我似乎无法在这里找到一个好的例子
一个快速简单的例子。假设我有以下视图模型:
public class PersonViewModel
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public Gender Gender{ get; set; }
public List<PhoneNumberViewModel> PhoneNumbers { get; set; }
}
使用PhoneNumberViewModel如下:
public class PhoneNumberViewModel
{
public string PhoneNumber { get; set; }
public string Extension { get; set; }
}
表单只是一个用电话号码显示人员信息的表单。他们可以添加或删除电话号码。
所有这些都是这样的简单形式:
<form id="personForm" action="@Url.Action("Person", "Home")" method="post">
@Html.AntiForgeryToken()
@Html.HiddenFor(model => model.Id)
@Html.LabelFor(model => model.FirstName, "First Name")
@Html.TextBoxFor(model => model.FirstName, new { @class = "form-control"})
@Html.LabelFor(model => model.LastName, "Last Name")
@Html.TextBoxFor(model => model.LastName, new { @class = "form-control"})
@Html.LabelFor(model => model.Gender, "Gender")
@Html.EnumDropDownListFor(model => model.Gender, new { @class = "form-control"})
@Html.LabelFor(model => model.DateOfBirth, "Date Of Birth")
@Html.TextBoxFor(model => model.DateOfBirth, new { @class = "form-control", type = "date"})
<table class="table table-striped">
<thead>
<tr>
<th>Extension</th>
<th>Phone Number</th>
</tr>
</thead>
<tbody>
@for (var i = 0; i < Model.PhoneNumbers.Count; ++i)
{
<tr>
<td>@Html.TextBoxFor(model => model.PhoneNumbers[i].Extension)</td>
<td>@Html.TextBoxFor(model => model.PhoneNumbers[i].PhoneNumber)</td>
</tr>
}
</tbody>
</table>
<button type="submit" id="savePersonForm" class="btn btn-success">Submit</button>
用这样一个简单的帖子:
var serializeForm = $("#personForm").serialize();
$.ajax({
url: action,
method: 'post',
contentType: "application/x-www-form-urlencoded",
data: serializeForm
}).done(function (response) {
// handle response
}).fail(function () {
// handle error
});
这很好用,除了这需要不断维护更新字段名称索引,以便它能正确绑定到控制器方法。如果不是PhoneNumbers在绑定控制器方法时将在PersonViewModel内部返回null。使用foreach循环而不是for也不会将PersonViewModel中的PhoneNumbers绑定到控制器方法,因为您没有跟上索引值。
这真的是人们在MVC中不断处理它以使其正确绑定的方式吗?如果您删除和/或添加行,请始终确保您的javascript更新名称值索引,并确保使用视图模型中的信息使javascript保持最新,因为可能会添加更多属性或删除以后?对我而言,这感觉就像是一种必须处理这个问题的“旧”方式。
谢谢!