如何爲枚舉創建默認編輯器模板?我的意思是:我可以做這樣的事情:如何爲枚舉創建默認編輯器模板?
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Enum>" %>
<% -- any code to read the enum and write a dropdown -->
,並把這個在EditorTemplates文件夾名稱Enum.ascx
下?
下面是我嘗試過的問題的解決方法,但這不是我所需要的。
這裏是我的枚舉:
public enum GenderEnum
{
/// <summary>
/// Male
/// </summary>
[Description("Male Person")]
Male,
/// <summary>
/// Female
/// </summary>
[Description("Female Person")]
Female
}
我做一個GenderEnum.acsx
模板,並把它放在Shared/EditorTemplates
文件夾中。這裏是模板:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<AlefTech.HumanResource.Core.GenderEnum>" %>
<%@ Import Namespace="AlefTech.HumanResource.WebModule.Classes" %>
<%=Html.DropDownListFor(m => m.GetType().Name, Model.GetType()) %>
當然的方法是我自己:
public static class HtmlHelperExtension
{
public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, Type enumType)
{
List<SelectListItem> list = new List<SelectListItem>();
Dictionary<string, string> enumItems = enumType.GetDescription();
foreach (KeyValuePair<string, string> pair in enumItems)
list.Add(new SelectListItem() { Value = pair.Key, Text = pair.Value });
return htmlHelper.DropDownListFor(expression, list);
}
/// <summary>
/// return the items of enum paired with its descrtioption.
/// </summary>
/// <param name="enumeration">enumeration type to be processed.</param>
/// <returns></returns>
public static Dictionary<string, string> GetDescription(this Type enumeration)
{
if (!enumeration.IsEnum)
{
throw new ArgumentException("passed type must be of Enum type", "enumerationValue");
}
Dictionary<string, string> descriptions = new Dictionary<string, string>();
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;
}
}
然而,即使這個工作對我來說,這不是我在問什麼。相反,我需要以下工作:
代碼Shared\EditorTemplates\Enum.acsx
:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Enum>" %>
<%@ Import Namespace="System.Web.Mvc.Html" %>
<%@ Import Namespace="WhereMyExtentionMethod" %>
<%=Html.DropDownListFor(m => m.GetType().Name, Model.GetType()) %>
有了這個,我就不用做每一個枚舉任何更多的模板。
你還沒有得到這個工作? 你介意發佈這裏使用的助手代碼:return htmlHelper.DropDownListFor(expression,list);? – 2010-08-09 18:15:12
順便說一句,如果您在模型的enum字段中放置了[UIHint(「Enum」)],則代碼應該可以工作,請將類型System.Web.Mvc.ViewUserControl更改爲動態,然後將它們轉換爲正確的類型在幫手電話:) –
2010-08-09 18:30:58