带有整数字符串的枚举

时间:2016-09-06 17:33:49

标签: c# asp.net asp.net-mvc

我有一个公开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,十四个月,十六个月,十八个月

我将如何做到这一点?

10 个答案:

答案 0 :(得分:4)

您可以查看此link

他的解决方案是针对Asp.NET,但通过简单的修改,您可以在MVC中使用它,如

<div>

帮助您构建Key和Value列表

/// <span class="code-SummaryComment"><summary></span>
/// Provides a description for an enumerated type.
/// <span class="code-SummaryComment"></summary></span>
[AttributeUsage(AttributeTargets.Enum | AttributeTargets.Field, 
 AllowMultiple = false)]
public sealed class EnumDescriptionAttribute :  Attribute
{
   private string description;

   /// <span class="code-SummaryComment"><summary></span>
   /// Gets the description stored in this attribute.
   /// <span class="code-SummaryComment"></summary></span>
   /// <span class="code-SummaryComment"><value>The description stored in the attribute.</value></span>
   public string Description
   {
      get
      {
         return this.description;
      }
   }

   /// <span class="code-SummaryComment"><summary></span>
   /// Initializes a new instance of the
   /// <span class="code-SummaryComment"><see cref="EnumDescriptionAttribute"/> class.</span>
   /// <span class="code-SummaryComment"></summary></span>
   /// <span class="code-SummaryComment"><param name="description">The description to store in this attribute.</span>
   /// <span class="code-SummaryComment"></param></span>
   public EnumDescriptionAttribute(string description)
       : base()
   {
       this.description = description;
   }
}

然后你将你的枚举装饰为

/// <span class="code-SummaryComment"><summary></span>
/// Provides a static utility object of methods and properties to interact
/// with enumerated types.
/// <span class="code-SummaryComment"></summary></span>
public static class EnumHelper
{
   /// <span class="code-SummaryComment"><summary></span>
   /// Gets the <span class="code-SummaryComment"><see cref="DescriptionAttribute" /> of an <see cref="Enum" /></span>
   /// type value.
   /// <span class="code-SummaryComment"></summary></span>
   /// <span class="code-SummaryComment"><param name="value">The <see cref="Enum" /> type value.</param></span>
   /// <span class="code-SummaryComment"><returns>A string containing the text of the</span>
   /// <span class="code-SummaryComment"><see cref="DescriptionAttribute"/>.</returns></span>
   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;
   }

   /// <span class="code-SummaryComment"><summary></span>
   /// Converts the <span class="code-SummaryComment"><see cref="Enum" /> type to an <see cref="IList" /> </span>
   /// compatible object.
   /// <span class="code-SummaryComment"></summary></span>
   /// <span class="code-SummaryComment"><param name="type">The <see cref="Enum"/> type.</param></span>
   /// <span class="code-SummaryComment"><returns>An <see cref="IList"/> containing the enumerated</span>
   /// type value and description.<span class="code-SummaryComment"></returns></span>
   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<Enum, string>(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");

希望它会帮助你

答案 1 :(得分:1)

制作枚举的扩展名描述

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 <Description> 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();
    }
}

}

答案 2 :(得分:1)

您可以使用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
}

参考:What's New in ASP.NET MVC 5.1

答案 3 :(得分:1)

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());

答案 4 :(得分:0)

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];

答案 5 :(得分:0)

除了使用描述属性(请参阅其他答案或使用Google)之外,我经常使用RESX文件,其中键是枚举文本(例如TwelveMonths),值是所需的文本。

然后,执行一个可以返回所需文本的函数并且为多语言应用程序翻译值也很容易。

我还想添加一些单元测试以确保所有值都有关联的文本。如果有一些例外(例如最后可能是Count值,则单元测试将排除检查中的那些。

所有这些东西都不是很难并且非常灵活。如果您使用DescriptionAttribute并希望获得多语言支持,则无论如何都需要使用资源文件。

通常,我会有一个类来获取每个需要显示的enum类型的值(显示名称)和每个资源文件一个单元测试文件,尽管我有一些其他类用于某些常见代码,例如比较密钥在资源文件中,单位测试的值为enum(并且一次重载允许指定异常)。

顺便说一下,在这种情况下,让enum的值与月份数相匹配(例如TwelveMonths = 12)是有意义的。在这种情况下,您还可以使用string.Format作为显示值,并在资源中也有例外(如单数)。

答案 6 :(得分:0)

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

您可以参考此链接Create a dropdown list from an Enum in Asp.Net MVC

答案 7 :(得分:0)

为您的解决方案发布模板,您可以根据需要更改某些部分。

定义用于格式化枚举的通用EnumHelper:

public abstract class EnumHelper<T> 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<T>(this HtmlHelper htmlHelper,
        string name,
        EnumHelper<T> enumHelper,
        string value = null,
        string nonSelected = null,
        IDictionary<string, object> htmlAttributes = null)
        where T : struct
    {
        List<SelectListItem> items = new List<SelectListItem>();

        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<OccupancyTimeline>
{
    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())

答案 8 :(得分:0)

我会采用略微不同且可能更简单的方法:

public static List<int> PermittedMonths = new List<int>{12, 14, 16, 18};

然后简单地说:

foreach(var permittedMonth in PermittedMonths)
{
    MyDropDownList.Items.Add(permittedMonth.ToString(), permittedMonth + " months");
}

以你描述的方式使用枚举我觉得可能有点陷阱。

答案 9 :(得分:0)

您可以使用转换为整数的 getter,而不是尝试从 Enum 的视图中绘制属性。我的问题是我将 enum 的值写为字符串,但我想要它的 int 值。

例如,您可以在视图模型类中具有以下两个属性:

public enum SomeEnum
{
   Test = 0,
   Test1 = 1,
   Test2,
}

public SomeEnum SomeEnum {get; init;}

public int SomeEnumId => (int) SomeEnum;

然后您就可以通过剃刀 enum 访问您的 View

<input type="hidden" asp-for="@Model.SomeEntityId" />