Liehuo. Net tutorials in MVC projects, Model usually refers to Entity Class. By default, the parameters of Action are the same as those defined by MapRoute. They are all loose and simple types. You must manually assign these parameters to the Model object attribute. Obviously, these codes are boring and boring (If your company issues a bonus based on the number of lines of code, skip this article). Fortunately, MVC provides automated operations for our lazy people.
See the following demo:
Public class MvcApplication: System. Web. HttpApplication { Public static void RegisterRoutes (RouteCollection routes) { ... Routes. MapRoute ( "Test ", "Test/{name}/{age }", New {controller = "Test", action = "Index", name = "", age = 0} ); ... } } Public class TestController: Controller { Public ActionResult Index (User user) { ViewData. Model = user; Return View (); } } Public class User { Public string Name {get; set ;} Public int Age {get; set ;} } |
When we request "/Test/Tom/23", we find that the user attribute of Index () is correctly assigned a value. Intelligent, stupid, right? How did this happen?
Public class ControllerActionInvoker: IActionInvoker { Protected virtual object GetParameterValue (controllerContext, parameterDescriptor) { ... IModelBinder binder = GetModelBinder (parameterDescriptor ); ... ModelBindingContext bindingContext = new ModelBindingContext () { FallbackToEmptyPrefix = (parameterDescriptor. BindingInfo. Prefix = null ), ModelName = parameterName, ModelState = controllerContext. Controller. ViewData. ModelState, ModelType = parameterType, PropertyFilter = propertyFilter, ValueProvider = valueProvider }; Object result = binder. BindModel (controllerContext, bindingContext ); Return result; } } |
Oh, magic comes from IModelBinder binder, which defaults to defamodelmodelbinder.
Public class DefaultModelBinder: IModelBinder { Public virtual object BindModel (controllerContext, ModelBindingContext bindingContext) { ... Return BindComplexModel (controllerContext, bindingContext ); } } |
DefaultModelBinder completes the final assignment operation through a large number of reflection internally, which can basically adapt to our daily development needs. If you are interested, you can view the implementation details by yourself. This article will not go into detail.
It must be noted that ModelBindingContext contains all the information required for the BindModel operation, including the ModelType, propertyFilter, and ModelState ), and the corresponding request value (valueProvider.
- Four pages in total:
- Previous Page
- 1
- 2
- 3
- 4
- Next Page