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.ViewUserControl<Enum>" %>
<% -- any code to read the enum and write a dropdown -->
And put this in the EditorTemplates folder under the name Enum.ascx
?
把它放在名为Enum.ascx的EditorTemplates文件夹中?
Here's a workaround for my problem that I tried, but it's not what I need.
这是我尝试过的问题的解决方法,但这不是我需要的。
Here is my Enum:
这是我的枚举:
public enum GenderEnum
{
/// <summary>
/// Male
/// </summary>
[Description("Male Person")]
Male,
/// <summary>
/// Female
/// </summary>
[Description("Female Person")]
Female
}
I made a template called GenderEnum.acsx
and put it in the Shared/EditorTemplates
folder. Here is the Template:
我创建了一个名为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()) %>
Of course the method is my own:
当然这个方法是我自己的:
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;
}
}
However, even though this worked for me, it is not what I'm asking. Instead, I need the following to work:
然而,尽管这对我有用,但这并不是我所要求的。相反,我需要以下工作:
Code for Shared\EditorTemplates\Enum.acsx
:
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()) %>
With this I wouldn't have to make a template for every enum any more.
有了这个,我就不用再为每个枚举制作一个模板了。
8 个解决方案
#1
18
Late to answer but I hope this helps others. Ideally you want all enums to use your Enum template by convention, not by specifying a UIHint each time, and you can accomplish that by creating a custom model metadata provider like this:
迟到回答,但我希望这有助于其他人。理想情况下,您希望所有枚举按惯例使用您的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;
}
}
Then simply register it in the Application_Start method of Global.asax.cs:
然后只需在Global.asax.cs的Application_Start方法中注册它:
ModelMetadataProviders.Current = new CustomMetadataProvider();
Now all your enum properties will use your Enum template by default.
现在,默认情况下,所有枚举属性都将使用您的枚举模板。
#2
7
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 <dynamic>
, i used instead <Enum>
in generic type.
谢谢你们的贡献Yngvebn,我之前尝试过你的解决方案(在你的最后评论中),但我唯一没做的是
at last the solution is :
create a template named Enum.acsx and put it under the Views\Shared\EditorTemplates
最后解决方案是:创建一个名为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())%>
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<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;
}
}
#3
5
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.
对于实际下拉列表中的文本,它将在资源文件中查找与枚举名称匹配的资源,否则只需编写实际的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());
}
You will also need my overloaded Tag-class if you want it to work with no rewriting..
如果你想让它在没有重写的情况下工作,你还需要我重载的Tag-class。
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;
}
}
#4
5
Nour Sabony, I modified your version to also support localization with resources. Therefore I changed the DescriptionAttribute to the DisplayAttribute of the DataAnnotations namespace
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;
}
The definition of an enum has to look like this now:
枚举的定义现在必须如下所示:
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,
}
it can be used in a View in the same way, e.g. (Razor):
它可以以相同的方式在视图中使用,例如(剃刀):
@Html.DropDownListFor(model => model.Gender, typeof(Gender))
Hope this helps someone!
希望这有助于某人!
#5
2
I made the dropdownlistfor method a bit easier and now you can give a selectedValue with it:
我使dropdownlistfor方法更容易了,现在你可以给它一个selectedValue:
public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, Type enumType)
{
return DropDownListFor(htmlHelper, expression, enumType, null);
}
public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, Type enumType, object selectedValue)
{
Dictionary<string, string> enumItems = enumType.GetDisplayNames(htmlHelper.ViewContext.HttpContext);
return htmlHelper.DropDownListFor(expression, new SelectList(enumItems, "Key", "Value", selectedValue));
}
Use it like this in your View:
在您的视图中使用它:
@Html.DropDownListFor(m => m.Gender, typeof(Gender), Model.Gender)
Model is my MVC Model and its property Gender contains the selectedValue for the DropDownListFor.
Model是我的MVC模型,其属性Gender包含DropDownListFor的selectedValue。
#6
1
I don't think there is a default way to define an editor for all enum types because you could want different behavior depending on the situation. For example, maybe you have a [Flags] enum and want multi select, or you want a dropdownlist, or you want radio buttons.
我认为没有一种默认方法可以为所有枚举类型定义编辑器,因为根据具体情况,您可能需要不同的行为。例如,你可能有一个[Flags]枚举并想要多选,或者你想要一个下拉列表,或者你想要单选按钮。
Plus, generally you are going to want some sort of meaningful display string beyond what you can accomplish in the variable naming limitations.
另外,通常您会想要某种有意义的显示字符串,超出了您在变量命名限制中可以实现的范围。
Certainly assigning to a property of type enum works out of the box but how you get that value is going to be up to you.
当然,分配给枚举类型的属性是开箱即用的,但是你如何得到这个值将取决于你。
#7
1
You can use this example.....
你可以用这个例子......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Profile.Data.Enum
{
public enum EfficiencyType
{
Good = 1,
Excelent = 2,
Better = 3
}
}
extension method is....
扩展方法是....
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
namespace Profile.Web.HtmlHelper
{
public static class EnumDropDownList
{
public static HtmlString EnumDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> modelExpression, string firstElement)
{
var typeOfProperty = modelExpression.ReturnType;
if (!typeOfProperty.IsEnum)
throw new ArgumentException(string.Format("Type {0} is not an enum", typeOfProperty));
var enumValues = new SelectList(Enum.GetValues(typeOfProperty));
return htmlHelper.DropDownListFor(modelExpression, enumValues, firstElement);
}
}
}
and the html is....
和HTML是....
@Html.DropDownListFor(model => model.EfficiencyType, new SelectList(Enum.GetValues(typeof(EfficiencyType)), Model.EfficiencyType), "--Select--")
#8
0
Yes
是
Almost sure this works out of the box.
几乎可以肯定这是开箱即用的。
Try naming your template the same name as your enum.
尝试使用与枚举相同的名称命名模板。
#1
18
Late to answer but I hope this helps others. Ideally you want all enums to use your Enum template by convention, not by specifying a UIHint each time, and you can accomplish that by creating a custom model metadata provider like this:
迟到回答,但我希望这有助于其他人。理想情况下,您希望所有枚举按惯例使用您的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;
}
}
Then simply register it in the Application_Start method of Global.asax.cs:
然后只需在Global.asax.cs的Application_Start方法中注册它:
ModelMetadataProviders.Current = new CustomMetadataProvider();
Now all your enum properties will use your Enum template by default.
现在,默认情况下,所有枚举属性都将使用您的枚举模板。
#2
7
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 <dynamic>
, i used instead <Enum>
in generic type.
谢谢你们的贡献Yngvebn,我之前尝试过你的解决方案(在你的最后评论中),但我唯一没做的是
at last the solution is :
create a template named Enum.acsx and put it under the Views\Shared\EditorTemplates
最后解决方案是:创建一个名为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())%>
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<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;
}
}
#3
5
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.
对于实际下拉列表中的文本,它将在资源文件中查找与枚举名称匹配的资源,否则只需编写实际的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());
}
You will also need my overloaded Tag-class if you want it to work with no rewriting..
如果你想让它在没有重写的情况下工作,你还需要我重载的Tag-class。
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;
}
}
#4
5
Nour Sabony, I modified your version to also support localization with resources. Therefore I changed the DescriptionAttribute to the DisplayAttribute of the DataAnnotations namespace
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;
}
The definition of an enum has to look like this now:
枚举的定义现在必须如下所示:
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,
}
it can be used in a View in the same way, e.g. (Razor):
它可以以相同的方式在视图中使用,例如(剃刀):
@Html.DropDownListFor(model => model.Gender, typeof(Gender))
Hope this helps someone!
希望这有助于某人!
#5
2
I made the dropdownlistfor method a bit easier and now you can give a selectedValue with it:
我使dropdownlistfor方法更容易了,现在你可以给它一个selectedValue:
public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, Type enumType)
{
return DropDownListFor(htmlHelper, expression, enumType, null);
}
public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, Type enumType, object selectedValue)
{
Dictionary<string, string> enumItems = enumType.GetDisplayNames(htmlHelper.ViewContext.HttpContext);
return htmlHelper.DropDownListFor(expression, new SelectList(enumItems, "Key", "Value", selectedValue));
}
Use it like this in your View:
在您的视图中使用它:
@Html.DropDownListFor(m => m.Gender, typeof(Gender), Model.Gender)
Model is my MVC Model and its property Gender contains the selectedValue for the DropDownListFor.
Model是我的MVC模型,其属性Gender包含DropDownListFor的selectedValue。
#6
1
I don't think there is a default way to define an editor for all enum types because you could want different behavior depending on the situation. For example, maybe you have a [Flags] enum and want multi select, or you want a dropdownlist, or you want radio buttons.
我认为没有一种默认方法可以为所有枚举类型定义编辑器,因为根据具体情况,您可能需要不同的行为。例如,你可能有一个[Flags]枚举并想要多选,或者你想要一个下拉列表,或者你想要单选按钮。
Plus, generally you are going to want some sort of meaningful display string beyond what you can accomplish in the variable naming limitations.
另外,通常您会想要某种有意义的显示字符串,超出了您在变量命名限制中可以实现的范围。
Certainly assigning to a property of type enum works out of the box but how you get that value is going to be up to you.
当然,分配给枚举类型的属性是开箱即用的,但是你如何得到这个值将取决于你。
#7
1
You can use this example.....
你可以用这个例子......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Profile.Data.Enum
{
public enum EfficiencyType
{
Good = 1,
Excelent = 2,
Better = 3
}
}
extension method is....
扩展方法是....
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
namespace Profile.Web.HtmlHelper
{
public static class EnumDropDownList
{
public static HtmlString EnumDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> modelExpression, string firstElement)
{
var typeOfProperty = modelExpression.ReturnType;
if (!typeOfProperty.IsEnum)
throw new ArgumentException(string.Format("Type {0} is not an enum", typeOfProperty));
var enumValues = new SelectList(Enum.GetValues(typeOfProperty));
return htmlHelper.DropDownListFor(modelExpression, enumValues, firstElement);
}
}
}
and the html is....
和HTML是....
@Html.DropDownListFor(model => model.EfficiencyType, new SelectList(Enum.GetValues(typeof(EfficiencyType)), Model.EfficiencyType), "--Select--")
#8
0
Yes
是
Almost sure this works out of the box.
几乎可以肯定这是开箱即用的。
Try naming your template the same name as your enum.
尝试使用与枚举相同的名称命名模板。