带有整数字符串的枚举
我有这样的公共enum
:
public enum occupancyTimeline { TwelveMonths, FourteenMonths, SixteenMonths, EighteenMonths }
我将用于DropDown
菜单,如下所示:
@Html.DropDownListFor(model => model.occupancyTimeline, new SelectList(Enum.GetValues(typeof(CentralParkLCPreview.Models.occupancyTimeline))), "")
现在我正在寻找我的价值观
12个月,14个月,16个月,18个月而不是TweleveMonths,十四个月,十六个月,十八个月
我怎么做到这一点?
您可以查看此链接
他的解决方案是针对Asp.NET,但通过简单的修改,你可以在MVC中使用它
/// /// Provides a description for an enumerated type. /// [AttributeUsage(AttributeTargets.Enum | AttributeTargets.Field, AllowMultiple = false)] public sealed class EnumDescriptionAttribute : Attribute { private string description; /// /// Gets the description stored in this attribute. /// /// The description stored in the attribute. public string Description { get { return this.description; } } /// /// Initializes a new instance of the /// class. /// /// The description to store in this attribute. /// public EnumDescriptionAttribute(string description) : base() { this.description = description; } }
帮助程序,允许您构建Key和Value列表
/// /// Provides a static utility object of methods and properties to interact /// with enumerated types. /// public static class EnumHelper { /// /// Gets the of an /// type value. /// /// The type value. /// A string containing the text of the /// . public static string GetDescription(Enum value) { if (value == null) { throw new ArgumentNullException("value"); } string description = value.ToString(); FieldInfo fieldInfo = value.GetType().GetField(description); EnumDescriptionAttribute[] attributes = (EnumDescriptionAttribute[]) fieldInfo.GetCustomAttributes(typeof(EnumDescriptionAttribute), false); if (attributes != null && attributes.Length > 0) { description = attributes[0].Description; } return description; } /// /// Converts the type to an /// compatible object. /// /// The type. /// An containing the enumerated /// type value and description. public static IList ToList(Type type) { if (type == null) { throw new ArgumentNullException("type"); } ArrayList list = new ArrayList(); Array enumValues = Enum.GetValues(type); foreach (Enum value in enumValues) { list.Add(new KeyValuePair(value, GetDescription(value))); } return list; } }
然后你装饰你的枚举
public enum occupancyTimeline { [EnumDescriptionAttribute ("12 months")] TwelveMonths, [EnumDescriptionAttribute ("14 months")] FourteenMonths, [EnumDescriptionAttribute ("16 months")] SixteenMonths, [EnumDescriptionAttribute ("18 months")] EighteenMonths }
您可以在控制器中使用它来填充下拉列表
ViewBag.occupancyTimeline =new SelectList( EnumHelper.ToList(typeof(occupancyTimeline)),"Value","Key");
在您的视图中,您可以使用以下内容
@Html.DropdownList("occupancyTimeline")
希望它能帮助你
我自己做了一个扩展方法,我现在在每个项目中使用它:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Web.Mvc; namespace App.Extensions { public static class EnumExtensions { public static SelectList ToSelectList(Type enumType) { return new SelectList(ToSelectListItems(enumType)); } public static List ToSelectListItems(Type enumType, Func
然后像这样使用它(例如在View.cshtml中)(为了清楚起见,代码分为两行;也可以使oneliner成为代码):
// A SelectList without default value selected var list1 = EnumExtensions.ToSelectListItems(typeof(occupancyTimeline)); @Html.DropDownListFor(model => model.occupancyTimeline, new SelectList(list1), "") // A SelectList with default value selected if equals "DesiredValue" // Selection is determined by lambda expression as a second parameter to // ToSelectListItems method which returns bool. var list2 = EnumExtensions.ToSelectListItems(typeof(occupancyTimeline), item => (occupancyTimeline)item == occupancyTimeline.DesiredValue)); @Html.DropDownListFor(model => model.occupancyTimeline, new SelectList(list2), "")
更新
根据Phil的建议,我已经更新了上面的代码,可以从某些资源中读取枚举的显示值(如果有的话)。 资源中项目的名称应采用Enum_
(例如Enum_occupancyTimeline_TwelveMonths
)。 这样,您可以在资源文件中为枚举值提供文本,而无需使用某些属性修饰枚举值。 资源类型(MyResource)直接包含在ToSelectItems方法中。 您可以将其提取为扩展方法的参数。
命名枚举值的另一种方法是应用描述属性(这不会使代码适应我所做的更改)。 例如:
public enum occupancyTimeline { [Description("12 Months")] TwelveMonths, [Description("14 Months")] FourteenMonths, [Description("16 Months")] SixteenMonths, [Description("18 Months")] EighteenMonths }
对枚举进行扩展描述
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Runtime.CompilerServices; using System.ComponentModel; public static class EnumerationExtensions { //This procedure gets the attribute of an enum constant, if any. //Otherwise, it gets the string name of then enum member. [Extension()] public static string Description(Enum EnumConstant) { Reflection.FieldInfo fi = EnumConstant.GetType().GetField(EnumConstant.ToString()); DescriptionAttribute[] attr = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false); if (attr.Length > 0) { return attr(0).Description; } else { return EnumConstant.ToString(); } } }
您可以使用EnumDropDownListFor
来实现此目的。 这是你想要的一个例子。 ( 只是不要忘记使用EnumDropDownListFor
你应该使用ASP MVC 5和Visual Studio 2015. ):
你的观点:
@using System.Web.Mvc.Html @using WebApplication2.Models @model WebApplication2.Models.MyClass @{ ViewBag.Title = "Index"; } @Html.EnumDropDownListFor(model => model.occupancyTimeline)
而你的模特:
public enum occupancyTimeline { [Display(Name = "12 months")] TwelveMonths, [Display(Name = "14 months")] FourteenMonths, [Display(Name = "16 months")] SixteenMonths, [Display(Name = "18 months")] EighteenMonths }
参考: ASP.NET MVC 5.1中的新增function
public namespace WebApplication16.Controllers{ public enum occupancyTimeline:int { TwelveMonths=12, FourteenMonths=14, SixteenMonths=16, EighteenMonths=18 } public static class MyExtensions { public static SelectList ToSelectList(this string enumObj) { var values = from occupancyTimeline e in Enum.GetValues(typeof(occupancyTimeline)) select new { Id = e, Name = string.Format("{0} Months",Convert.ToInt32(e)) }; return new SelectList(values, "Id", "Name", enumObj); } } }
用法
@using WebApplication16.Controllers @Html.DropDownListFor(model => model.occupancyTimeline,Model.occupancyTimeline.ToSelectList());
public enum occupancyTimeline { TwelveMonths=0, FourteenMonths=1, SixteenMonths=2, EighteenMonths=3 } public string[] enumString = { "12 Months", "14 Months", "16 Months", "18 Months"}; string selectedEnum = enumString[(int)occupancyTimeLine.TwelveMonths];
要么
public enum occupancyTimeline { TwelveMonths, FourteenMonths, SixteenMonths, EighteenMonths } public string[] enumString = { "12 Months", "14 Months", "16 Months", "18 Months"}; string selectedEnum = enumString[DropDownList.SelectedIndex];
除了使用属性进行描述(参见其他答案或使用Google)之外,我经常使用RESX文件,其中键是枚举文本(例如, TwelveMonths
),值是所需的文本。
然后,执行一个返回所需文本的函数并且很容易为多语言应用程序转换值也是相对微不足道的。
我还想添加一些unit testing,以确保所有值都有关联的文本。 如果有一些例外(比如最后可能是一个Count
值,那么unit testing将排除那些来自检查的那些)。
所有这些东西都不是很难并且非常灵活。 如果您使用DescriptionAttribute
并希望获得多语言支持,则无论如何都需要使用资源文件。
通常,我会有一个类来获取每个需要显示的enum
类型的值(显示名称)和每个资源文件一个unit testing文件,尽管我有一些其他类用于某些常见代码,例如比较资源文件中的键和enum
值用于unit testing(并且一个重载允许指定exception)。
顺便说一句,在这样的情况下,让enum
的值与月数匹配是TwelveMonths = 12
(例如, TwelveMonths = 12
)。 在这种情况下,您还可以将string.Format
用于显示的值,并在资源中也有例外(如单数)。
MVC 5.1
@Html.EnumDropDownListFor(model => model.MyEnum)
MVC 5
@Html.DropDownList("MyType", EnumHelper.GetSelectList(typeof(MyType)) , "Select My Type", new { @class = "form-control" })
MVC 4
您可以参考此链接从Asp.Net MVC中的Enum创建下拉列表
发布解决方案的模板,您可以根据需要更改某些部分。
定义通用EnumHelper以形成枚举:
public abstract class EnumHelper where T : struct { static T[] _valuesCache = (T[])Enum.GetValues(typeof(T)); public virtual string GetEnumName() { return GetType().Name; } public static T[] GetValuesS() { return _valuesCache; } public T[] GetValues() { return _valuesCache; } virtual public string EnumToString(T value) { return value.ToString(); } }
定义MVC通用下拉列表扩展帮助程序:
public static class SystemExt { public static MvcHtmlString DropDownListT(this HtmlHelper htmlHelper, string name, EnumHelper enumHelper, string value = null, string nonSelected = null, IDictionary htmlAttributes = null) where T : struct { List items = new List (); if (nonSelected != null) { items.Add(new SelectListItem() { Text = nonSelected, Selected = string.IsNullOrEmpty(value), }); } foreach (T item in enumHelper.GetValues()) { if (enumHelper.EnumToIndex(item) >= 0) items.Add(new SelectListItem() { Text = enumHelper.EnumToString(item), Value = item.ToString(), //enumHelper.Unbox(item).ToString() Selected = value == item.ToString(), }); } return htmlHelper.DropDownList(name, items, htmlAttributes); } }
任何时候你需要格式化一些枚举定义EnumHelper特定枚举T:
public class OccupancyTimelineHelper : EnumHelper { public override string EnumToString(occupancyTimeline value) { switch (value) { case OccupancyTimelineHelper.TwelveMonths: return "12 Month"; case OccupancyTimelineHelper.FourteenMonths: return "14 Month"; case OccupancyTimelineHelper.SixteenMonths: return "16 Month"; case OccupancyTimelineHelper.EighteenMonths: return "18 Month"; default: return base.EnumToString(value); } } }
最后使用View中的代码:
@Html.DropDownListT("occupancyTimeline", new OccupancyTimelineHelper())
我会采用略有不同,也许更简单的方法:
public static List PermittedMonths = new List {12, 14, 16, 18};
那简单地说:
foreach(var permittedMonth in PermittedMonths) { MyDropDownList.Items.Add(permittedMonth.ToString(), permittedMonth + " months"); }
以你描述的方式使用枚举我觉得可能有点陷阱。