我正在尝试使用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。使用此属性作为源。

其他回答

您希望使用类似Enum的东西。getvalue

更新-我建议使用下面的符文建议,而不是这个选项!


我猜你想要的是下面这样的话:

<select name="blah">
    <option value="1">Movie</option>
    <option value="2">Game</option>
    <option value="3">Book</option>
</select>

你可以用一个扩展方法来做,如下所示:

public static string DropdownEnum(this System.Web.Mvc.HtmlHelper helper,
                                  Enum values)
{
    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    sb.Append("<select name=\"blah\">");
    string[] names = Enum.GetNames(values.GetType());
    foreach(string name in names)
    {
        sb.Append("<option value=\"");
        sb.Append(((int)Enum.Parse(values.GetType(), name)).ToString());
        sb.Append("\">");
        sb.Append(name);
        sb.Append("</option>");
    }
    sb.Append("</select>");
    return sb.ToString();
}

但这类内容是无法本土化的(游戏邦注:即很难将其翻译成其他语言)。

注意:你需要调用静态方法的枚举实例,即Html.DropdownEnum(ItemTypes.Movie);

也许有一种更优雅的方式来做到这一点,但上面的方法确实有效。

好吧,我真的是姗姗姗迟了,但无论如何,我已经在博客上讨论了这个主题,在这个主题中我创建了一个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() });
    }
}

在。net Core中,你可以这样做:

@Html.DropDownListFor(x => x.Foo, Html.GetEnumSelectList<MyEnum>())

一个超级简单的方法来做到这一点-没有所有的扩展似乎过度的东西是:

你的枚举:

    public enum SelectedLevel
    {
       Level1,
       Level2,
       Level3,
       Level4
    }

在你的控制器内部,将Enum绑定到一个List:

    List<SelectedLevel> myLevels = Enum.GetValues(typeof(SelectedLevel)).Cast<SelectedLevel>().ToList();

然后把它扔进ViewBag:

    ViewBag.RequiredLevel = new SelectList(myLevels);

最后简单地将它绑定到视图:

    @Html.DropDownList("selectedLevel", (SelectList)ViewBag.RequiredLevel, new { @class = "form-control" })

这是迄今为止我发现的最简单的方法,不需要任何扩展或任何疯狂的东西。

更新:见安德鲁斯下面的评论。