如何在HtmlHelper中调用`EditorExtensions.EditorFor`?

我在CreateView中使用不同的模型,所有模型都inheritance自BaseModel。 调用正确的EditorFor我创建了一个获取Model和实际属性的HtmlHelper。 但我不知道如何调用它。

BaseModel:

public abstract class BaseModel { protected IEnumerable PropertyInfoCache { get; set; } protected IEnumerable EnumeratedPropertyCache { get; set; } protected BaseModel() { PropertyInfoCache = this.GetType().GetProperties(); EnumeratedPropertyCache = PropertyInfoCache.Select(p=> new EnumeratedProperty(p.Name,p.GetType())); } public IEnumerable 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) ); } } 

EditorFor识别对象的类型,所以你想要做的是从EnumeratedProperty类中的值中提取类型,而不是直接传递类,并从中传递值。