【发布时间】:2012-10-17 14:08:13
【问题描述】:
我正在尝试构建一个通用模型绑定器,它使用反射将属性分配给从 BindingContext 检索的指定类型的对象。所以是这样的:
public class ModelBinder : IModelBinder
{
public object BindModel<T, K> (ControllerContext controllerContext, ModelBindingContext bindingContext)
where T : class, new()
where K : class
{
Type ObjectType = typeof(T);
Type InterfaceType = typeof(K);
T obj = new T();
foreach (var Property in ObjectType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance))
{
Type PropertyType = Property.PropertyType;
// checks if property is a custom data object
if (!(PropertyType.GetGenericArguments().Count() > 0 && PropertyType.GetGenericArguments()[0].GetInterfaces().Contains(InterfaceType)))
{
Property.SetValue(obj, bindingContext.ValueProvider.GetValue(Property.Name), null);
}
}
return obj;
}
显然这不起作用,因为它没有正确实现 IModelBinder 接口。这样的事情可能吗?
编辑:
为了详细说明我这样做的原因,我们的对象使用了许多不同的自定义对象。例如,Class 对象:
public class Class : ModelBase<Class>
{
public Class () { }
public virtual string ClassDescription { get; set; }
public virtual string ClassName { get; set; }
public virtual LookUp ClassType { get; set; }
public virtual double Credits { get; set; }
public virtual bool Documents { get; set; }
public virtual LookUp PracticeArea { get; set; }
}
使用 LookUp 类:
public class LookUp : ModelBase<LookUp>
{
public LookUp () { }
public virtual string DisplayName { get; set; }
public virtual LookUpType Type { get; set; }
}
下拉列表用于查找和其他对象,因此我的 Class/Create 自定义模型绑定器将执行以下操作:
LookUp ClassType = LookUp.Load(long.Parse(bindingContext.ValueProvider.GetValue("ClassType").AttemptedValue))
我不明白如何使用 DefaultModelBinder 来处理这样的事情。
【问题讨论】:
-
为什么需要这样的模型活页夹?为什么 DefaultModelBinder 不适合您?它已经使用反射来分配模型的值。
-
我还没有使用 DefaultModelBinder 的经验,但如果失败了,那是我的备用计划。
-
DefaultModelBinder 应该可以工作。如果你有一些特定的场景,它会毫不犹豫地回来,描述这个场景并提出一个具体的问题。
-
我在使用 DefaultModelBinder 时遇到的问题是我的很多对象都包含其他自定义对象的属性。因此,我总是必须创建一个自定义绑定器实现 IModelBinder。我看不出如何使用 DefaultModelBinder 来处理这个问题。
-
DefaultModelBinder 适用于任何复杂和嵌套的属性。您所要做的就是在请求中传递正确的密钥。在这里阅读:haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
标签: c# asp.net-mvc reflection