How to make a default editor template for enums?

前端 未结 7 993
星月不相逢
星月不相逢 2020-12-08 03:11

How can I make a default editor template for enums? By which I mean: can I do something like this:

<%@ Control Language=\"C#\" Inherits=\"System.Web.Mvc.V         


        
相关标签:
7条回答
  • 2020-12-08 03:49

    Here's a helper I made for this.. In your View you can simply do:

    <%= Html.DropDownForEnum<MyEnum>("some-name-for-dropdown", MyEnum.TheFirstValue) %>
    

    for the text in the actual dropdown it will look for a Resource in the resource-file that matches the name of the enum, otherwise just write the actual Enumtext itself.

    public static MvcHtmlString DropDownForEnum<T>(this HtmlHelper h, string name, T selectedValue)
    {
        Type enumType = typeof(T);
        Tag t = new Tag("select").With("name", name).And("id", name);
    
        foreach (T val in Enum.GetValues(enumType))
        {
            string enumText = Resources.ResourceManager.GetString(val.ToString());
            if (String.IsNullOrEmpty(enumText)) enumText = val.ToString();
            Tag option = new Tag("option").With("value", (val).ToString()).AndIf(val.Equals(selectedValue), "selected", "selected").WithText(enumText);
            t.Append(option);
        }
        return MvcHtmlString.Create(t.ToString());
    }
    

    You will also need my overloaded Tag-class if you want it to work with no rewriting..

    public class Tag : TagBuilder
    {
    public Tag (string TagName): base(TagName)
    {
    
    }
    
    public Tag Append(Tag innerTag)
    {
        base.InnerHtml += innerTag.ToString();
        return this;
    }
    
    public Tag WithText(string text)
    {
    
        base.InnerHtml += text;
        return this;
    }
    
    public Tag With(Tag innerTag)
    {
        base.InnerHtml = innerTag.ToString();
        return this;
    }
    
    public Tag With(string attributeName, string attributeValue)
    {
        base.Attributes.Add(attributeName, attributeValue);
        return this;
    }
    
    public Tag And(string attributeName, string attributeValue)
    {
        base.Attributes.Add(attributeName, attributeValue);
        return this;
    }
    
    
    public Tag AndIf(bool condition, string attributeName, string attributeValue)
    {
        if(condition)
            base.Attributes.Add(attributeName, attributeValue);
        return this;
    }
    }
    
    0 讨论(0)
提交回复
热议问题