【问题标题】:Unable to cast object of type Person to type PersonViewModel无法将 Person 类型的对象转换为 PersonViewModel 类型
【发布时间】: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


【解决方案1】:

看起来这与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}
}

试试这个;如果您在下方发帖仍有问题,我会提供帮助。

【讨论】:

  • 嘿,它似乎仍然无法正常工作。我更改了我的代码以反映您的更改,但绑定中为空。现在发送的数据看起来像 Persons[0].FirstName
  • 听起来您还需要在视图中进行更改 - Model.People 而不是 Model.Persons
【解决方案2】:

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

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

对您的项目的变量引用

  • DeploymentPath:您的项目的网址
  • ControllerName : SavePeople() 函数的控制器名称
  • 操作名称:SavePeople
  • 参数名称:vm
  • _input:你的 Person 对象

一旦您的 ajax 函数能够执行,您就可以直接访问 SavePeople 操作中的值,使用 vm.Persons - 这是一个列表。

【讨论】:

    【解决方案3】:

    假设您没有自定义序列化设置,型号为@model HomeController.PersonViewModel。以下表达式有效

    @Html.TextBoxFor(x => @Model.Persons[i].FirstName)
    

    如果没有任何效果,只需使用 IFormCollection 并手动解析值或调试 Model Binding 中的特定问题。

    public JsonResult SavePeople(IFormCollection vm)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-06
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多