How can I invoke `EditorExtensions.EditorFor` in my HtmlHelper?

北战南征 提交于 2019-12-08 12:41:41

问题


I use different Models in my CreateView, all inherit from BaseModel. To call the right EditorFor I have created a HtmlHelper that gets the Model and the actual property. But I don´t know how to invoke it.

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

in my View:

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

回答1:


EditorFor recognizes the type of an object, so what you would want to do is extract the type from the value in the EnumeratedProperty class, instead of passing the class directly, and pass in the value from it too.



来源:https://stackoverflow.com/questions/6533316/how-can-i-invoke-editorextensions-editorfor-in-my-htmlhelper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!