Asp.Net Mvc: Model Binding 机制分析2011-11-21 博客园 tristanguo环境:Windows 2008, VS 2008 SP1, Asp.Net Mvc RC1请求过程片段:在请求的Action被调用之前,ControllerActionInvoker.InvokeAction()方法被调用,在这个方法里 面,有一个ReflectedActionDescriptor的实例会被构建,这个实例包含Action的描述信息。接着,ControllerActionInvoker.GetParameterValues()方法被调用,通过传入的之前创建的 ReflectedActionDescriptor实例,获取Action参数列表(对应的ParameterDescriptor的实例分别被创建 ),进而遍历各参数,尝试获取参数的值,在遍历的循环里面, ControllerActionInvoker.GetParameterValue()方法被调用。以下就是ControllerActionInvoker.GetParameterValue()方法的源代码:
protected virtual object GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) { // collect all of the necessary binding properties Type parameterType = parameterDescriptor.ParameterType; IModelBinder binder = GetModelBinder(parameterDescriptor); IDictionary<string, ValueProviderResult> valueProvider = controllerContext.Controller.ValueProvider; string parameterName = parameterDescriptor.BindingInfo.Prefix ?? parameterDescriptor.ParameterName; Predicate<string> propertyFilter = GetPropertyFilter(parameterDescriptor); // finally, call into the binder ModelBindingContext bindingContext = new ModelBindingContext() { FallbackToEmptyPrefix = (parameterDescriptor.BindingInfo.Prefix == null), // only fall back if prefix not specified ModelName = parameterName, ModelState = controllerContext.Controller.ViewData.ModelState, ModelType = parameterType, PropertyFilter = propertyFilter, ValueProvider = valueProvider }; object result = binder.BindModel(controllerContext, bindingContext); return result; }