ASP. NET has no magic-binding and parsing ASP. net mvc model (part II), asp. netmvc
Previous Article ASP. NET has no magic -- ASP. net mvc model binding analysis (part I) This article introduces ASP.. net mvc model binding related components and concepts. This chapter describes how the Controller completes model binding through these components during execution. The main contents of this chapter include:
● Model binding process
○ Get ModelBinder
○ Obtain ValueProvider
○ Create ModelMetadata
○ Model binding
● Defamodelmodelbinder model binding process
○ Simple model binding
○ Complex model binding
● Summary
Model binding process
Previous articles have introduced the creation and execution of Controller in MVC (see ASP. NET has no magic -- ASP. net mvc Controller instantiation and execution). The execution process includes temporary data loading, obtaining the Action Method Name,Action Method executionAnd temporary data storage.
The model binding process is actually included in the execution of the Action method (ActionInvoker. in the InvokeAction method), the previous article ASP. NET has no magic -- ASP. net mvc Filter also introduces the execution of Action from the perspective of the Filter, one of which is that when the authorization Filter is executed completely and the authorization is passed, other filters and Action methods will be executed, for example:
The core code for executing the Action method is as follows:
The GetParameterValues method in the code is used to obtain the Action parameter based on the context of the Controller and the description of the Action, that is, the model binding process. The Code is as follows:
The code above gets the parameter array of the Action, traverses the array, binds a single parameter through the GetParameterValue method, and finally uses the parameter name as the Key, the bound value is returned when the object is stored in the dictionary. The code for the GetParameterValue method is as follows:
From the code, the entire binding process involves the following steps:
1. Get ModelBinder according to the parameter.
2. Obtain the value provider from the Controller.
3. Create a model binding context. The context includes Metadata, model name, and value provider.
4. Bind the model with the obtained ModelBinder.
Next, we will analyze these core steps.
Get ModelBinder
Call the GetModelBinder method in the Code and obtain a ModelBinder Based on the parameter information, which is the implementation code:
You can see from the code that there are two ways to get ModelBinder. First, you can obtain the ModelBinder applied to this parameter by using the parameter description information (ParameterDescriptor, the core code is as follows (ParameterDescriptor uses ReflectedParameterDescriptor by default and obtains features through reflection ):
Note: