且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么是 ASP.NET MVC 中的模型绑定?

更新时间:2022-11-23 13:28:00

ModelBinding 是 ASP.NET MVC 用于从输入创建强类型对象(或填充原始类型参数)的机制流(通常是 HTTP 请求).

ModelBinding is the mechanism ASP.NET MVC uses to create strongly-typed objects (or fill primitive-type parameters) from the input stream (usually an HTTP request).

例如,考虑这个 Person 模型:

For example, consider this Person model:

public class Person
{
     public string Name { get; set; }
     public int Age { get; set; }
}

现在,您在某些 Controller 中有一些 Action 需要 Person 类型作为参数:

Now, you have some Action in some Controller that's expecting a Person type as a parameter:

public class HomeController : Controller
{
      public ActionResult EditPersonDetails(Person person)
      {
          // ...
      }
}

Model-Binder 然后负责为您填充 person 参数.默认情况下,它通过查询 ValueProviders 集合并询问(待绑定)模型中每个属性的值来实现.

The Model-Binder is then responsible to fill that person parameter for you. By default it does it by consulting the ValueProviders collection and asking for the value of each property in the (to be bound) model.

http://haacked.com/archive/2011/06/30/whatrsquos-the-difference-between-a-value-provider-and-model-binder.aspx/