Nou*_*uny 20 asp.net asp.net-mvc enums mvc-editor-templates
如何为枚举创建默认编辑器模板?我的意思是:我可以做这样的事情:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Enum>" %>
<% -- any code to read the enum and write a dropdown -->
Run Code Online (Sandbox Code Playgroud)
并将其放在EditorTemplates文件夹下的名称下Enum.ascx?
这是我尝试过的问题的解决方法,但这不是我需要的.
这是我的枚举:
public enum GenderEnum
{
/// <summary>
/// Male
/// </summary>
[Description("Male Person")]
Male,
/// <summary>
/// Female
/// </summary>
[Description("Female Person")]
Female
}
Run Code Online (Sandbox Code Playgroud)
我制作了一个名为的模板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()) %>
Run Code Online (Sandbox Code Playgroud)
当然这个方法是我自己的:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
然而,尽管这对我有用,但这不是我所要求的.相反,我需要以下工作:
代码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()) %>
Run Code Online (Sandbox Code Playgroud)
有了这个,我就不用再为每个枚举制作模板了.
Tod*_*ier 18
迟到回答,但我希望这有助于其他人.理想情况下,您希望所有枚举按惯例使用您的Enum模板,而不是每次都指定UIHint,您可以通过创建这样的自定义模型元数据提供程序来实现:
using System;
using System.Collections.Generic;
using System.Web.Mvc;
public class CustomMetadataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName) {
var mm = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
if (modelType.IsEnum && mm.TemplateHint == null) {
mm.TemplateHint = "Enum";
}
return mm;
}
}
Run Code Online (Sandbox Code Playgroud)
然后只需在Global.asax.cs的Application_Start方法中注册它:
ModelMetadataProviders.Current = new CustomMetadataProvider();
Run Code Online (Sandbox Code Playgroud)
现在,默认情况下,所有枚举属性都将使用您的枚举模板.
谢谢你们的贡献
Yngvebn,我之前尝试过你的解决方案(在你的最后评论中),但我唯一没做的就是<dynamic>,我用的<Enum>是通用类型.
最后解决方案是:
创建一个名为Enum.acsx的模板,并将其放在Views\Shared\EditorTemplates下
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<%@ Import Namespace="System.Web.Mvc.Html" %>
<%@ Import Namespace="the extension methods namespace" %>
<% Enum model = (Enum)Model; %>
<%=Html.DropDownList(model.GetType().Name,model.GetType())%>
Run Code Online (Sandbox Code Playgroud)
在您的实体中:
public class Person
{
[UIHint("Enum")]
public GenderEnum Gender{get;set;}
}
public Enum GenderEnum
{
[Description("Male Person")]
Male,
[Description("Female Person")]
Female
}
Run Code Online (Sandbox Code Playgroud)
并且还有扩展方法:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
这是我为此做的一个帮手..在你的视图中你可以简单地做:
<%= Html.DropDownForEnum<MyEnum>("some-name-for-dropdown", MyEnum.TheFirstValue) %>
Run Code Online (Sandbox Code Playgroud)
对于实际下拉列表中的文本,它将在资源文件中查找与枚举名称匹配的资源,否则只需编写实际的Enumtext本身.
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());
}
Run Code Online (Sandbox Code Playgroud)
如果你想要它没有重写,你还需要我重载的Tag类.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
Nour Sabony,我修改了你的版本,也支持资源本地化.因此,我将DescriptionAttribute更改为DataAnnotations命名空间的DisplayAttribute
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.GetDisplayNames(htmlHelper.ViewContext.HttpContext);
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 DisplayName.
/// </summary>
/// <param name="enumeration">enumeration type to be processed.</param>
/// <returns></returns>
public static Dictionary<string, string> GetDisplayNames(this Type enumeration, HttpContextBase httpContext)
{
if (!enumeration.IsEnum)
{
throw new ArgumentException("passed type must be of Enum type", "enumerationValue");
}
Dictionary<string, string> displayNames = new Dictionary<string, string>();
var members = enumeration.GetMembers().Where(m => m.MemberType == MemberTypes.Field);
foreach (MemberInfo member in members)
{
var attrs = member.GetCustomAttributes(typeof(DisplayAttribute), false);
if (attrs.Count() != 0)
if (((DisplayAttribute)attrs[0]).ResourceType != null)
{
displayNames.Add(member.Name, ((DisplayAttribute)attrs[0]).GetName(););
}
else
{
displayNames.Add(member.Name, ((DisplayAttribute)attrs[0]).Name);
}
}
return displayNames;
}
Run Code Online (Sandbox Code Playgroud)
枚举的定义现在必须如下所示:
public enum Gender
{
[Display(Name = "Male", ResourceType = typeof(mynamespace.App_LocalResources.Shared))]
Male = 1,
[Display(Name = "Female", ResourceType = typeof(mynamespace.App_LocalResources.Shared))]
Female = 2,
}
Run Code Online (Sandbox Code Playgroud)
它可以以相同的方式在视图中使用,例如(Razor):
@Html.DropDownListFor(model => model.Gender, typeof(Gender))
Run Code Online (Sandbox Code Playgroud)
希望这有助于某人!
| 归档时间: |
|
| 查看次数: |
8481 次 |
| 最近记录: |