如何在HtmlHelper中调用"EditorExtensions.EditorFor"

本文关键字:quot EditorExtensions EditorFor 调用 HtmlHelper | 更新日期: 2023-09-27 18:00:50

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

基本型号:

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) );
    }
}

如何在HtmlHelper中调用"EditorExtensions.EditorFor"

EditorFor可以识别对象的类型,因此您要做的是从EnumeratedProperty类中的值中提取类型,而不是直接传递类,并从中传递值。