问题描述
我正在尝试向服务器发送数据的表单数组,但是它无法正确绑定。
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集合中。
解决方法
这似乎也遭受了ASP.NET MVC Model Binding with jQuery ajax request
中标识的同一错误MVC中存在一个错误,他们拒绝修复如果集合属性名称以类型名称开头但不会绑定的问题。
尝试更改:
public class PersonViewModel
{
public List<Person> Persons {get; set}
}
收件人:
public class PersonViewModel
{
public List<Person> People {get; set}
}
尝试一下;如果您仍然无法在下面发布信息,我会为您提供帮助。
,首先,请确保您的ajax正常工作。
return $.ajax({
contentType: 'application/json; charset=utf-8',url: DeploymentPath + '/ControllerName/ActionName',type: "POST",data: JSON.stringify({ "parameterName": _input})
});
对项目的可变引用
- DeploymentPath:您项目的网址
- ControllerName:SavePeople()函数的控制器名称
- 动作名称: SavePeople
- parameterName: vm
- _input:您的Person对象
一旦您的ajax函数能够执行,您就可以使用vm.Persons
-这是一个列表,直接在 SavePeople 操作中访问该值。
假设您尚未自定义序列化设置和模型为@model HomeController.PersonViewModel
。以下表达作品
@Html.TextBoxFor(x => @Model.Persons[i].FirstName)
如果没有任何效果,请使用IFormCollection并手动解析值或调试Model Binding中的特定问题。
public JsonResult SavePeople(IFormCollection vm)