我想使用模型绑定来让我的控制器看起来更干净,您可以看到使用模型绑定有多好:

public ActionResult Create(Person personToCreate)
{
    //Create person here
}

public ActionResult Create(string firstName, string lastName, string address, string phoneNum, string email, string postalCode, string city, string province, string country)
{
    //Create person here
}

在进行模型绑定时,我们只需使用具有正确名称的表单即可 Html.TextBox("")

那么 jquery 呢?我怎样才能确保当我做一个 $.post(url, data, callback, dataType) 或一个 $.ajax(options) 拨电至 Create(Person personToCreate) Person 对象是否被正确填充?

有帮助吗?

解决方案

你需要:

  1. 使数据中的属性名称与绑定类型名称的参数/属性匹配。
  2. 始终为绑定类型的所有不可空参数/属性提供值。

第二点是最重要的,因为绑定到 person 的行为与为每个属性指定单独的操作参数的行为不同。如果您的类型具有名为“Foo”的不可空属性,则无法在表单中提供 foo 项将阻止绑定。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top