我正在尝试使用Html。下拉列表扩展方法,但不知道如何与枚举一起使用它。

假设我有一个这样的枚举:

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

我如何去创建一个下拉与这些值使用Html。下拉列表扩展方法?

或者我最好的办法是简单地创建一个for循环并手动创建Html元素?


当前回答

我在这一点上已经很晚了,但我刚刚发现了一个非常酷的方法,用一行代码就可以做到这一点,如果你愿意添加Unconstrained Melody NuGet包(来自Jon Skeet的一个漂亮的小库)。

这个解决方案更好,因为:

它确保(使用泛型类型约束)值确实是一个枚举值(由于Unconstrained Melody) 它避免了不必要的装箱(由于无约束旋律) 它缓存所有的描述,以避免在每个调用上使用反射(由于Unconstrained Melody) 它比其他解决方案的代码更少!

所以,下面是让它工作的步骤:

在包管理器控制台中,“Install-Package UnconstrainedMelody” 在你的模型上添加一个属性,如下所示: //用你的枚举类型替换"YourEnum public IEnumerable<SelectListItem> AllItems { 得到 { 返回Enums.GetValues < YourEnum >()。Select(enumValue => new SelectListItem {Value = enumValue. tostring (), Text = enumValue. getdescription ()}); } }

现在您已经在模型上公开了SelectListItem的列表,您可以使用@Html。下拉列表或@Html。使用此属性作为源。

其他回答

所以没有扩展函数,如果你正在寻找简单和容易..这就是我所做的

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

where XXXXX.Sites.YYYY.Models.State是enum

也许做辅助函数更好,但是当时间很短的时候,这将完成工作。

现在这个特性在MVC 5.1中通过@Html.EnumDropDownListFor()得到了开箱即用的支持。

查看以下链接:

https://learn.microsoft.com/en-us/aspnet/mvc/overview/releases/mvc51-release-notes#Enum

根据上面的投票,微软花了5年的时间来实现这样一个如此受欢迎的功能,真是太遗憾了!

我遇到了同样的问题,发现了这个问题,并认为Ash提供的解决方案不是我要寻找的;与内置的HTML . dropdownlist()函数相比,必须自己创建HTML意味着更少的灵活性。

c# 3等使得这非常简单。我有一个名为TaskStatus的枚举:

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

这将创建一个很好的ol' SelectList,可以像在视图中一样使用:

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

匿名类型和LINQ使它更加优雅。无意冒犯,阿什。:)

好吧,我真的是姗姗姗迟了,但无论如何,我已经在博客上讨论了这个主题,在这个主题中我创建了一个EnumHelper类,它可以实现非常简单的转换。

http://jnye.co/Posts/4/creating-a-dropdown-list-from-an-enum-in-mvc-and-c%23

在你的控制器中:

//If you don't have an enum value use the type
ViewBag.DropDownList = EnumHelper.SelectListFor<MyEnum>();

//If you do have an enum value use the value (the value will be marked as selected)    
ViewBag.DropDownList = EnumHelper.SelectListFor(MyEnum.MyEnumValue);

在您看来:

@Html.DropDownList("DropDownList")
@* OR *@
@Html.DropDownListFor(m => m.Property, ViewBag.DropDownList as SelectList, null)

helper类:

public static class EnumHelper
{
    // Get the value of the description attribute if the   
    // enum has one, otherwise use the value.  
    public static string GetDescription<TEnum>(this TEnum value)
    {
        var fi = value.GetType().GetField(value.ToString());

        if (fi != null)
        {
            var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

            if (attributes.Length > 0)
            {
                return attributes[0].Description;
            }
        }

        return value.ToString();
    }

    /// <summary>
    /// Build a select list for an enum
    /// </summary>
    public static SelectList SelectListFor<T>() where T : struct
    {
        Type t = typeof(T);
        return !t.IsEnum ? null
                         : new SelectList(BuildSelectListItems(t), "Value", "Text");
    }

    /// <summary>
    /// Build a select list for an enum with a particular value selected 
    /// </summary>
    public static SelectList SelectListFor<T>(T selected) where T : struct
    {
        Type t = typeof(T);
        return !t.IsEnum ? null
                         : new SelectList(BuildSelectListItems(t), "Text", "Value", selected.ToString());
    }

    private static IEnumerable<SelectListItem> BuildSelectListItems(Type t)
    {
        return Enum.GetValues(t)
                   .Cast<Enum>()
                   .Select(e => new SelectListItem { Value = e.ToString(), Text = e.GetDescription() });
    }
}
@Html.DropDownListFor(model => model.Type, Enum.GetNames(typeof(Rewards.Models.PropertyType)).Select(e => new SelectListItem { Text = e }))