我在CreateView中使用不同的模型,所有模型都继承自BaseModel。调用正确的EditorFor我已经创建了一个获取Model和实际属性的HtmlHelper。但我不知道如何调用它。
BaseModel:
public abstract class BaseModel
{
protected IEnumerable<PropertyInfo> PropertyInfoCache { get; set; }
protected IEnumerable<EnumeratedProperty> EnumeratedPropertyCache { get; set; }
protected BaseModel()
{
PropertyInfoCache = this.GetType().GetProperties();
EnumeratedPropertyCache = PropertyInfoCache.Select(p=> new EnumeratedProperty(p.Name,p.GetType()));
}
public IEnumerable<EnumeratedProperty> EnumerateProperties()
{
return EnumeratedPropertyCache;
}
public object GetPropertyValue(string PropertyName)
{
var property = PropertyInfoCache.SingleOrDefault(i=>i.Name==PropertyName);
if(property!=null)
return property.GetValue(this,null);
return null;
}
}
public class EnumeratedProperty
{
public string Name { get; private set; }
public Type Type { get; private set; }
public EnumeratedProperty(string PropertyName, Type PropertyType)
{
this.Name = PropertyName;
this.Type = PropertyType;
}
}
在我的观点中:
@foreach (var property in Model.EnumerateProperties())
{
@Html.EditorForProperty(Model,property);
}
的HtmlHelper:
public static class ExtensionMethods
{
public static MvcHtmlString EditorForProperty(this HtmlHelper html, BaseModel Model, EnumeratedProperty property)
{
// creates an error: The type arguments for method 'EditorFor' cannot be inferred from the usage. Try specifying the type arguments explicitly.
return System.Web.Mvc.Html.EditorExtensions.EditorFor(html, Model => Model.GetPropertyValue(property.Name) );
}
}
答案 0 :(得分:0)
EditorFor可识别对象的类型,因此您要做的是从EnumeratedProperty类中的值中提取类型,而不是直接传递类,并从中传递值。