次のようなオブジェクトがあるとします。
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"} ] }}