asp.net MVC 中枚举创建下拉列表?

我将尝试使用 Html.DropDownList 扩展方法,但不能找出如何使用它的枚举

让我们说我有一个这样的枚举:

public enum ItemTypes
{
    Movie = 1,
    Game = 2,
    Book = 3
}

如何着手创建下拉列表,这些值,使用 HTML'>Html.DropDownList 扩展名的方法?或者是我最好的方法,只需创建的循环,并手动创建 html 元素吗?

解决方法 1:                    

我滚进扩展方法的符文的答案:

public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
{
  var values = from TEnum e in Enum.GetValues(typeof(TEnum))
               select new { ID = e, Name = e.ToString() };

  return new SelectList(values, "Id", "Name", enumObj);
}

这使您可以编写:

ViewData["taskStatus"] = task.Status.ToSelectList();

解决方法 2:                    

我碰见了同样的问题,发现这个问题,并不是我在找什么 ; 灰而提供的解决方案的思想不必自己创建的 HTML 意味着少比作内置的 Html.DropDownList() 功能的灵活性。

原来 C# 3 等使这很容易。我有一个叫了任务状态的枚举:

var statuses = from TaskStatus s in Enum.GetValues(typeof(TaskStatus))
               select new { ID = s, Name = s.ToString() };
ViewData["taskStatus"] = new SelectList(statuses, "ID", "Name", task.Status);

这将创建好的又 SelectList,像用来在视图中可用:

<td><b>Status:</b></td><td><%=Html.DropDownList("taskStatus")%></td></tr>

匿名类型和 LINQ 使这得更优雅的个人谦逊。没有犯罪意图,灰。:)

解决方法 3:                    

扩展企业和符文的答案,如果你想有你的选择列表项地图,枚举类型的整数值,而不是字符串值的值属性,请使用下面的代码:

public static SelectList ToSelectList<TEnum>(this TEnum enumObj) where TEnum : struct {
    if(!typeof(TEnum).IsEnum) throw new ArgumentException("An Enumeration type is required.", "enumObj");

    var values = from TEnum e in Enum.GetValues(typeof(TEnum))
                 select new { ID = (int)e, Name = e.ToString() };

    return new SelectList(values, "ID", "Name", enumObj);
}

当作一个 TEnum 对象中的每个枚举值,而不是,我们可以把它当作一个对象,然后将其转换为整数,以获取未装箱的值。

注意:我还添加了一个泛型类型约束限制的类型,此扩展插件用于仅结构 (枚举的基类型),并确保传递中的结构实际上是枚举的运行时类型验证。

解决方法 4:                    

这样不扩展功能,如果您正在寻找简单和容易...这是我做的事

<%= Html.DropDownListFor(x => x.CurrentAddress.State, new SelectList(Enum.GetValues(typeof(XXXXX.Sites.YYYY.Models.State))))%>

凡 XXXXX。Sites.YYYY.Models.State 是一个枚举

可能更好地做 helper 函数,但是短时间时,这会完成这项工作。

解决方法 5:                    

Html.DropDownFor 只需要的例子,所以企业的解决方案的替代方法是,如下所示。

此外,你真的不必 genericize 扩展方法,您可以使用 enumValue.GetType(),而不是 typeof(T)。

    public static IEnumerable<SelectListItem> ToSelectList(this Enum enumValue)
    {
        return from Enum e in Enum.GetValues(enumValue.GetType())
               select new SelectListItem
                          {
                              Selected = e.Equals(enumValue),
                              Text = e.ToString(),
                              Value = e.ToString()
                          };
    }

解决方法 6:                    

你想看看使用类似Enum.GetValues

解决方法 7:                    

要解决这个问题,得到的数字,而不是使用企业的扩展方法的文本。

public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
{
  var values = from TEnum e in Enum.GetValues(typeof(TEnum))
               select new { ID = (int)Enum.Parse(typeof(TEnum),e.ToString())
                         , Name = e.ToString() };

  return new SelectList(values, "Id", "Name", enumObj);
}

解决方法 8:                    

我知道我迟到,一方,但认为您可能会发现此变体很有用,如这一还允许您使用描述性字符串,而不是枚举常量在下拉。为此,装饰用 [System.ComponentModel.Description] 属性的每个枚举项。

例如:

public enum TestEnum
{
  [Description("Full test")]
  FullTest,

  [Description("Incomplete or partial test")]
  PartialTest,

  [Description("No test performed")]
  None
}

这里是我的代码:

 private static Type GetNonNullableModelType(ModelMetadata modelMetadata)
    {
        Type realModelType = modelMetadata.ModelType;

        Type underlyingType = Nullable.GetUnderlyingType(realModelType);
        if (underlyingType != null)
        {
            realModelType = underlyingType;
        }
        return realModelType;
    }

    private static readonly SelectListItem[] SingleEmptyItem = new[] { new SelectListItem { Text = "", Value = "" } };

    public static string GetEnumDescription<TEnum>(TEnum value)
    {
        FieldInfo fi = value.GetType().GetField(value.ToString());

        DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

        if ((attributes != null) && (attributes.Length > 0))
            return attributes[0].Description;
        else
            return value.ToString();
    }

    public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression)
    {
        return EnumDropDownListFor(htmlHelper, expression, null);
    }

    public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, object htmlAttributes)
    {
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        Type enumType = GetNonNullableModelType(metadata);
        IEnumerable<TEnum> values = Enum.GetValues(enumType).Cast<TEnum>();

        IEnumerable<SelectListItem> items = from value in values
            select new SelectListItem
            {
                Text = GetEnumDescription(value),
                Value = value.ToString(),
                Selected = value.Equals(metadata.Model)
            };

        // If the enum is nullable, add an 'empty' item to the collection
        if (metadata.IsNullableValueType)
            items = SingleEmptyItem.Concat(items);

        return htmlHelper.DropDownListFor(expression, items, htmlAttributes);
    }

然后可以在您的视图中:

<%: Html.EnumDropDownListFor(model => model.MyEnumProperty) %>

希望这有助于您 !

解决方法 9:                    

这是我的帮助器方法的版本。我使用它:

var values = from int e in Enum.GetValues(typeof(TEnum))
             select new { ID = e, Name = Enum.GetName(typeof(TEnum), e) };

而不是,:

var values = from TEnum e in Enum.GetValues(typeof(TEnum))
           select new { ID = (int)Enum.Parse(typeof(TEnum),e.ToString())
                     , Name = e.ToString() };

在这里:

public static SelectList ToSelectList<TEnum>(this TEnum self) where TEnum : struct
    {
        if (!typeof(TEnum).IsEnum)
        {
            throw new ArgumentException("self must be enum", "self");
        }

        Type t = typeof(TEnum);

        var values = from int e in Enum.GetValues(typeof(TEnum))
                     select new { ID = e, Name = Enum.GetName(typeof(TEnum), e) };

        return new SelectList(values, "ID", "Name", self);
    }

解决方法 10:                    

嗨,

我试着企业的解决方案,看起来很酷,只遇见了一个重要的问题。在此扩展方法的 selectList,DataValue 不是常数的枚举,但 DataText 相同的索引。我有:

<select id="type" name="type">
<option value="Item1">Item1</option>
<option selected="selected" value="Item2">Item2</option>
<option value="Item3">Item3</option>
</select>

和我想要:

<select id="type" name="type">
<option value="1">Item1</option>
<option selected="selected" value="2">Item2</option>
<option value="3">Item3</option>
</select>

感谢您的帮助

解决方法 11:                    

此扩展方法的另一个修补程序的当前版本没有选择枚举的当前值。我定的最后一行:

public static SelectList ToSelectList<TEnum>(this TEnum enumObj) where TEnum : struct
    {
        if (!typeof(TEnum).IsEnum) throw new ArgumentException("An Enumeration type is required.", "enumObj");

        var values = from TEnum e in Enum.GetValues(typeof(TEnum))
                       select new
                       {
                           ID = (int)Enum.Parse(typeof(TEnum), e.ToString()),
                           Name = e.ToString()
                       };


        return new SelectList(values, "ID", "Name", ((int)Enum.Parse(typeof(TEnum), enumObj.ToString())).ToString());
    }

解决方法 12:                    

如果您想要添加本地化支持只需更改的 s.toString() 方法,是这样的:

ResourceManager rManager = new ResourceManager(typeof(Resources));
var dayTypes = from OperatorCalendarDay.OperatorDayType s in Enum.GetValues(typeof(OperatorCalendarDay.OperatorDayType))
               select new { ID = s, Name = rManager.GetString(s.ToString()) };

在这里,typeof(Resources) 是要加载的资源,然后你也很有用,如果您的枚举值包含多个单词的本地化的字符串。

 

 

 

 在一次项目中需要把枚举的值添加到Combox中去,需要对枚举进行操作。经过学习总结如下,也便于以后查询:
public enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 };
1.根据name获得Enum的类型:
Colors mycolor = (Colors)Enum.Parse(typeof(Colors),"red",true);
(int)mycolor1=1
2.根据value获得Enum的类型:
Colors mycolor = (Colors)Enum.Parse(typeof(Colors),"1",true);
mycolor2.ToString()=Red
3.遍历枚举内容
foreach(string s in Enum.GetNames(typeof(Colors)))
{
    //to do
}
4.怎样确定一个名称或值是枚举中的一个
Enum.IsDefined(typeof(myenum),object(name or value))
5.怎样确定一个类型:  Type t = mycolor.GetType();
                   Type t1 =typeof(Colors);
                   Type t2 = Type.GetType("namespace.Colors");
补充:
Colors myOrange = (Colors)Enum.Parse(typeof(Colors), "Red, Blue,Yellow");
The myOrange value has the combined entries of [myOrange.ToString()]=13

Colors myOrange2 = (Colors)Enum.Parse(typeof(Colors), "Red, Blue");
The myOrange2 value has the combined entries of [myOrange2.ToString()]=5

另:
x.gettype和typeof的用法
1.判断某个实例是否某个类型
  c#  o is classname
  vb   typeof o is classname//必须是引用类型。typeof且必须和is联用
2.c# typeof(int)
   bv gettype(integer)
3.object类的方法
   c# o.GetType
   vb  o.GetType

posted @ 2015-09-07 12:03  bxzjzg  阅读(557)  评论(0编辑  收藏  举报