如何创建从ASP.NET MVC的枚举一个DropDownList? [英] How do you create a dropdownlist from an enum in ASP.NET MVC?

查看:324
本文介绍了如何创建从ASP.NET MVC的枚举一个DropDownList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用Html.DropDownList扩展方法,但无法弄清楚如何使用枚举使用它。

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

 公开枚举ItemTypes
{
    电影= 1,
    游戏= 2,
    书= 3
}

我如何去创造与使用Html.DropDownList扩展方法,这些值的下拉列表?或者是简单地创建一个for循环和手动创建HTML元素我最好的选择?


解决方案

对于MVC V5.1使用Html.EnumDropDownListFor

  @ Html.DropDownList(MyType的
   Html.GetEnumSelectList(typeof运算(的MyType)),
   选择我喜欢的类型
   新{@class =表格控})


对于MVC V5使用EnumHelper

  @ Html.DropDownList(MyType的
   EnumHelper.GetSelectList(typeof运算(的MyType)),
   选择我喜欢的类型
   新{@class =表格控})


有关的MVC> 5和下

我滚符文的回答到一个扩展方法:

 命名空间MyApp.Common
{
    公共静态类MyExtensions {
        公共静态的SelectList ToSelectList< TEnum>(这TEnum选项myEnum)
            其中,TEnum:结构,IComparable的,IFormattable,IConvertible
        {
            在Enum.GetValues​​从TEnumËVAR值=(typeof运算(TEnum))
                选择新的{ID = E,名称= e.ToString()};
            返回新的SelectList(价值观,ID,姓名,选项myEnum);
        }
    }
}

这允许你写的:

 计算机[taskStatus] = task.Status.ToSelectList();

使用MyApp.Common

I'm trying to use the Html.DropDownList extension method but can't figure out how to use it with an enumeration.

Let's say I have an enumeration like this:

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

How do I go about creating a dropdown with these values using the Html.DropDownList extension method? Or is my best bet to simply create a for loop and create the html elements manually?

解决方案

For MVC v5.1 use Html.EnumDropDownListFor

@Html.DropDownList("MyType", 
   Html.GetEnumSelectList(typeof(MyType)) , 
   "Select My Type", 
   new { @class = "form-control" })


For MVC v5 use EnumHelper

@Html.DropDownList("MyType", 
   EnumHelper.GetSelectList(typeof(MyType)) , 
   "Select My Type", 
   new { @class = "form-control" })


For MVC >5 and lower

I rolled Rune's answer into an extension method:

namespace MyApp.Common
{
    public static class MyExtensions{
        public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
            where TEnum : struct, IComparable, IFormattable, IConvertible
        {
            var values = from TEnum e in Enum.GetValues(typeof(TEnum))
                select new { Id = e, Name = e.ToString() };
            return new SelectList(values, "Id", "Name", enumObj);
        }
    }
}

This allows you to write:

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

by using MyApp.Common

这篇关于如何创建从ASP.NET MVC的枚举一个DropDownList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆