標籤:des style blog io ar color os sp for
頁面綁定簡單類型的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; }......}
就可以通過遍曆各層屬性就行複雜類型值的擷取了。。。
MVC如何綁定複雜類型的頁面Model