【发布时间】:2011-03-26 18:45:34
【问题描述】:
如何为枚举创建默认编辑器模板?我的意思是:我可以这样做吗:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Enum>" %>
<% -- any code to read the enum and write a dropdown -->
并把它放在名称为Enum.ascx的EditorTemplates文件夹中?
这是我尝试解决的问题的解决方法,但这不是我需要的。
这是我的枚举:
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);?
-
顺便说一句,如果您将 [UIHint("Enum")] 放在模型中的枚举字段上,您的代码应该可以工作,将类型 System.Web.Mvc.ViewUserControl
更改为动态的,并将它们转换为助手调用中的正确类型:)
标签: asp.net asp.net-mvc enums mvc-editor-templates