无法将类型为 Person 的对象转换为类型 PersonViewModel

Unable to cast object of type Person to type PersonViewModel

我正在尝试向我的服务器发送一个数据表单数组,但它没有正确绑定。

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

中确定的相同错误有关

There is a bug in MVC they refuse to fix that if the colection property name begins with the type name it does not bind.

尝试更改:

public class PersonViewModel
{
    public List<Person> Persons {get; set}
}

收件人:

public class PersonViewModel
{
    public List<Person> People {get; set}
}

试试这个;如果您在下方仍然遇到问题 post,我会提供帮助。

首先,请确保您的 ajax 正常工作。

return $.ajax({
    contentType: 'application/json; charset=utf-8',
    url: DeploymentPath + '/ControllerName/ActionName',
    type: "POST",
    data: JSON.stringify({ "parameterName": _input})
});

您项目的变量引用

  • 部署路径:url 到您的项目
  • ControllerName:SavePeople() 函数的控制器名称
  • 动作名称:SavePeople
  • 参数名称: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)