【问题标题】:How to create a dropdownlist from an enum in ASP.NET MVC? [duplicate]如何从 ASP.NET MVC 中的枚举创建下拉列表? [复制]
【发布时间】:2016-08-22 05:15:43
【问题描述】:

我正在尝试使用 Html.DropDownList 扩展方法,但不知道如何将它与枚举一起使用。

我的课:

namespace Support_A_Tree.Models
{
    public enum Countries
    {
        Belgium,
        Netherlands,
        France,
        United_Kingdom,
        Other
    }


    [MetadataType(typeof(SupporterMetaData))]
    public partial class Person
    {
        public string Name { get; set; }
        public Countries Country { get; set; }

        public List<SelectListItem> allCountries()
        {
            List<SelectListItem> choices = new List<SelectListItem>();
            foreach (String c in Enum.GetValues(typeof(Countries)))
            {
                choices.Add(new SelectListItem() { Text = c , Value = bool.TrueString });
            }
            return choices;
        }


    }

    public class SupporterMetaData
    {
        public string Name { get; set; }

        [Required]
        public Countries Country { get; set; }
    }
}

在我的视图中,我试图获取所有国家/地区,但似乎我做错了。

@using (Html.BeginForm())
{
    <div>
        <p style = "color: red;">@ViewBag.Message</p>
    </div>

    <div>
        <h2> You want to ... </h2>
        <p>Plant trees</p>
        @Html.CheckBoxSimple("support", new { @value = "Plant trees" })

        <p>Support us financial</p>
        @Html.CheckBoxSimple("support", new { @value = "Support financial" })
    </div>

    <input type="submit" value="Continue ">
}

【问题讨论】:

标签: asp.net asp.net-mvc


【解决方案1】:

在你看来你可以使用SelectExtensions.EnumDropDownListFor:

例如:

@Html.EnumDropDownListFor(model => model.Countries)

假设视图的@model 有一个名为Countries 的属性,它是一个enum 类型。

如果您想在下拉菜单中显示默认文本(例如:“选择国家/地区”)。看看下面的问题和答案。

Html.EnumDropdownListFor: Showing a default text

【讨论】:

    猜你喜欢
    • 2010-09-28
    • 2013-08-26
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    相关资源
    最近更新 更多