【发布时间】:2020-12-04 22:28:12
【问题描述】:
我正在尝试向我的服务器发送一个表单数据数组,但它没有正确绑定。
public class PersonViewModel
{
public List<Person> Persons {get; set}
}
public class Person{
public string FirstName {get; set;}
}
// view model that wil render all the partial view models showing all the people
@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { id="people-form" autocomplete = "off" }))
{
<div class="container">
@for (int i = 0; i < Model.Persons.Count; i++)
{
<div>
<label>
@Html.TextBoxFor(x => x.Persons[i].FirstName)
</label>
</div>
}
</div>
}
// ajax used to post, trying to serialize it as an array but still when it hits my action it is not binding.
return $.ajax({
method: 'POST',
url: 'SavePeople',
data: $('#people-form').serializeArray(),
}).done(function (response) {
}).fail(function (err) {
});
[HttpPost]
public JsonResult SavePeople(PersonViewModel vm /* this comes in as null */)
{
}
发送的数据看起来像Persons[0].FirstName: 41441,但出于某种原因,它试图将其直接绑定到 PersonViewModel 而不是将其添加到 Persons 集合中。
【问题讨论】:
-
顺便说一句,你应该发送类似 { people: [ firstName: 'test']}
-
确实没有发送 json,我正在序列化生成 Persons%5B0%5D.FirstName=55353 的整个表单,如果它不在集合中,它将绑定但作为集合会导致问题。
标签: c# jquery ajax serialization asp.net-mvc-5