ASP.Net MVC ModelBindingContext class— how are its model values populated?

前端 未结 3 466
一生所求
一生所求 2020-12-31 18:20

I\'m scratching my head a bit at how model binders do their work in ASP.Net MVC.

To be specific, the BindModel() method has a ModelBindingContext parameter that ho

3条回答
  •  臣服心动
    2020-12-31 19:01

    The ModelBindingContext "knows" the type of model it's being handed because you have to either:

    • Add a ModelBinder attribute to your model
    • Register the ModelBinder with your model using the ModelBinders.Binders.Add() method.

    Example of ModelBinder attribute:

    [ModelBinder(typeof(ContactBinder))]
    public class Contact { ... }
    

    Example of ModelBinders.Binders.Add():

    void Application_Start()
    {
      ModelBinders.Binders[typeof(Contact)] = new ContactBinder();
    }
    

    If you have registered your ModelBinder and have implemented the BindModel method:

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { ... }
    
    1. Query the ModelBindingContext.ModelType is equal to your Model e.g.

      if (bindingContext.ModelType == typeof(Contact)) { ... }
      
    2. Rehydrate your model from the ModelBindingContext.ValueProvider property to retrieve ValueProviderResult instances that represent the data from form posts, route data, and the query string e.g.

      bindingContext.ValueProvider["Name"].AttemptedValue;
      

    The following books were used ASP.NET MVC 2 in Action and ASP.NET MVC 1.0 Quickly

提交回复
热议问题