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