如下面的代码片段所示绑定到参数上的数据具有三个来源HTTPPOST FormRouteData的Values和DataTokens属性它们都是字典结构的数据集合如果参数类型为字符串或者简单的值类型我们可以直接根据参数名称和Key进行匹配对于复杂类型(比如之前例子中定义的包含Controller和Action名称的数据类型SimpleModel)则通过反射根据类型创建新的对象并根据属性名称与Key的匹配关系对相应的属性进行赋值
public class DefaultModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext
stringmodelName Type modelType)
{
if (modelTypeIsValueType || typeof(string) == modelType)
{
object instance;
if (GetValueTypeInstance(controllerContext modelName
modelType out instance))
{
return instance;
};
returnActivatorCreateInstance(modelType)
}
objectmodelInstance = ActivatorCreateInstance(modelType)
foreach (PropertyInfo property in modelTypeGetProperties())
{
if (!propertyCanWrite || (!propertyPropertyTypeIsValueType
&&propertyPropertyType!=typeof(string)))
{
continue;
}
objectpropertyValue;
if (GetValueTypeInstance(controllerContext propertyName
propertyPropertyType out propertyValue))
{
propertySetValue(modelInstance propertyValue null)
}
}
returnmodelInstance;
}
private boolGetValueTypeInstance(ControllerContext controllerContext
stringmodelName Type modelType out object value)
{
var form = HttpContextCurrentRequestForm;
string key;
if (null != form)
{
key = formAllKeysFirstOrDefault(k =>stringCompare(k
modelName true) == )
if (key != null)
{
value = ConvertChangeType(form[key] modelType)
return true;
}
}
key = controllerContextRequestContextRouteDataValues
Where(item =>stringCompare(itemKey modelName true) == )
Select(item =>itemKey)FirstOrDefault()
if (null != key)
{
value = ConvertChangeType(controllerContextRequestContext
RouteDataValues[key] modelType)
return true;
}
key = controllerContextRequestContextRouteDataDataTokens
Where(item =>stringCompare(itemKey modelName true) == )
Select(item =>itemKey)FirstOrDefault()
if (null != key)
{
value = ConvertChangeType(controllerContextRequestContext
RouteDataDataTokens[key] modelType)
return true;
}
value = null;
return false;
}
}
返回目录ASPNET MVC 框架揭秘
编辑推荐
ASP NET开发培训视频教程
Microsoft NET框架程序设计视频教程
Java程序性能优化让你的Java程序更快更稳定
Visual C++音频/视频技术开发与实战
[] []