假设我有一个这样的对象:
public class Widget
{
public string Name { get; set; }
public IEnumerable<Foo> Foos { get; set; }
}
public class Foo
{
public string Name { get; set; }
}
我的控制器方法将它发送到这样的视图:
var widget = _dataAccess.GetWidget(someKey);
return View(widget);
我有一个看起来像这样的视图:
@model MyNamespace.Widget
@using(Html.BeginForm("Edit", "Widgets", FormMethod.Post, new { id = "the-form" }))
{
<p>@Html.TextBoxFor</p>
@foreach(var foo in Model.Foos)
{
<p>@Html.TextBoxFor(x => x.Foos.ToList()[Model.Foos.ToList().IndexOf(foo)])</p>
}
<input type="button" value="Save Changes" id="the-button" />
}
<script type="text/javascript">
$(function () {
$("#the-button").click(function () {
$.ajax({
url: '@Url.Action("Edit", "Widgets")',
type: 'POST',
data: JSON.stringify({ widget: serializeForm("the-form") }),
// etc, etc, not important
});
});
});
function serializeForm(formId) {
var formData = {};
$.each($("#" + formId).serializeArray(), function(){
formData[this.name] = $(this).val();
});
return formData;
}
</script>
序列化为:
{ "widget": { "Name" : "value from textbox", "[0].Name" : "some value", "[1].Name" : "some other value" } }
当然,这里的序列化没有帮助,因为[0].Name
它不可用。有没有办法改变它,使其序列化为 Post 方法控制器操作所期望的?即,类似:
{ "widget":{"Name":"blah", "Foos":[ { "Name":"foo name 1"}, { "Name":"foo name 2"} ] }}