您的位置:首页 > 其它

MVC如何绑定复杂类型的页面Model

2014-12-09 20:34 281 查看
  页面绑定简单类型的model时,可以在控制器里直接拿到页面绑定的model中post回来的值,但是如果一个model是复杂类型,比如model中有另一个自定义对象,这样的model就无法在控制器里面直接获取到值了。

  这时候就只能按层次的获取每个层次的值,具体如何实现代码如下:

public class SimpleModelBinder:IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
object model = this.GetModel(controllerContext, bindingContext.ModelType, bindingContext.ValueProvider, bindingContext.ModelName);
if (bindingContext.FallbackToEmptyPrefix && null == model)
{
model = this.GetModel(controllerContext, bindingContext.ModelType, bindingContext.ValueProvider, "");

}
return model;
}

public object GetComplexModel(ControllerContext controllerContex,Type modelType,IValueProvider valueProvider,string prefix)
{
object oModel = CreateModel(modelType);
PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(modelType);
foreach (PropertyDescriptor pd in pdc)
{
if (pd.IsReadOnly)
{
continue;
}
string key = string.IsNullOrEmpty(prefix) ? pd.Name : prefix + "." + pd.Name;

pd.SetValue(oModel,GetModel(controllerContex,pd.PropertyType,valueProvider,key));
}
return oModel;
}

public virtual object GetModel(ControllerContext controllerContext,Type modelType,IValueProvider valueProvider,string key) {
if (!valueProvider.ContainsPrefix(key))
{
return null;
}
ModelMetadata modelMeatadata = ModelMetadataProviders.Current.GetMetadataForType(null, modelType);
if (!modelMeatadata.IsComplexType)
{
return valueProvider.GetValue(key).ConvertTo(modelType);
}
if(modelMeatadata.IsComplexType)
{
return GetComplexModel(controllerContext, modelType, valueProvider, key);
}
return null;
}

private object CreateModel(Type modelType)
{
Type type = modelType;
if (modelType.IsGenericType)
{
Type genericTypeDefinition = modelType.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(IDictionary<,>))
{
type = typeof(Dictionary<,>).MakeGenericType(modelType.GetGenericArguments());
}
else if (((genericTypeDefinition == typeof(IEnumerable<>)) || (genericTypeDefinition == typeof(ICollection<>))) || (genericTypeDefinition == typeof(IList<>)))
{
type = typeof(List<>).MakeGenericType(
modelType.GetGenericArguments());
}
}
return Activator.CreateInstance(type);
}

}


然后

[ModelBinder(typeof(SimpleModelBinder))]
public class RoleModel
{
public string RoleName { set; get; }
public string RoleDescription { set; get; }
public string RoleExistId { set; get; }

public UserMangerModle userManagerModel { set; get; }
......
}
就可以通过遍历各层属性就行复杂类型值的获取了。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: