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
Thank you all for your contributions
Yngvebn, i tried your solution (in your last comment) before, but the only thing i didn't do is the , i used instead in generic type.
at last the solution is :
create a template named Enum.acsx and put it under the Views\Shared\EditorTemplates
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%@ Import Namespace="System.Web.Mvc.Html" %>
<%@ Import Namespace="the extension methods namespace" %>
<% Enum model = (Enum)Model; %>
<%=Html.DropDownList(model.GetType().Name,model.GetType())%>
and in your Entity:
public class Person
{
[UIHint("Enum")]
public GenderEnum Gender{get;set;}
}
public Enum GenderEnum
{
[Description("Male Person")]
Male,
[Description("Female Person")]
Female
}
and again there is Extention Methods:
public static class HtmlHelperExtension
{
public static MvcHtmlString DropDownListFor(this HtmlHelper htmlHelper, Expression> expression, Type enumType)
{
List list = new List();
Dictionary enumItems = enumType.GetDescription();
foreach (KeyValuePair pair in enumItems)
list.Add(new SelectListItem() { Value = pair.Key, Text = pair.Value });
return htmlHelper.DropDownListFor(expression, list);
}
///
/// return the items of enum paired with its descrtioption.
///
/// enumeration type to be processed.
///
public static Dictionary GetDescription(this Type enumeration)
{
if (!enumeration.IsEnum)
{
throw new ArgumentException("passed type must be of Enum type", "enumerationValue");
}
Dictionary descriptions = new Dictionary();
var members = enumeration.GetMembers().Where(m => m.MemberType == MemberTypes.Field);
foreach (MemberInfo member in members)
{
var attrs = member.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs.Count() != 0)
descriptions.Add(member.Name, ((DescriptionAttribute)attrs[0]).Description);
}
return descriptions;
}
}