如何在asp.net mvc中使用带有DescriptionAttribute的枚举

San*_*ams 14 c# asp.net enums asp.net-mvc-5.2 enumdropdownlistfor

我是asp.net MVC的新手.我试图在我的视图页面上使用下拉控件,该页面从枚举中填充.我还想为下拉列表添加自定义描述.我搜索了很多例子,但没有人发布如何在视图页面上填充描述.这是我的代码:

视图模型:

public enum SearchBy
    {
        [Description("SID/PID")]
        SID = 1,
        [Description("Name")]
        Name,
        [Description("Birth Date")]
        DOB,
        [Description("Cause#")]
        Cause
    }
Run Code Online (Sandbox Code Playgroud)

Index.cshtml

<div class="form-horizontal">
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group form-inline">
        @Html.LabelFor(model => model.searchBy, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EnumDropDownListFor(model => model.searchBy, "Search By", htmlAttributes: new { @class = "form-control" })
            @Html.TextBox("searchByVal", null, htmlAttributes: new { @placeholder = "SID / PID ", @class = "form-control" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @placeholder = "First Name", @class = "form-control" } })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @placeholder = "Last Name", @class = "form-control" } })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.DOB, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.DOB, new { htmlAttributes = new { @placeholder = "Birth Date", @class = "form-control" } })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.CauseNumber, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.CauseNumber, new { htmlAttributes = new { @placeholder = "Cause#", @class = "form-control" } })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Search" class="btn btn-block btn-primary" />
        </div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

它没有填充我的SearchBy枚举中提到的描述字段.看到这里的图像. http://postimg.org/image/phdxgocj7/ 请帮助我,我犯了错误.谢谢

更新: 我从Nico那里得到了解决方案.我对此进行了一些研究.我正在使用解决方案更新这篇文章,因为它可能对其他人有用,他们是MVC的新手 http://weblogs.asp.net/jongalloway//looking-at-asp-net-mvc-5-1-and-web- API-2-1部分-1-概述和-枚举

谢谢你们.享受编码..

Nic*_*ico 25

Html帮助器EnumDropDownListForEnumDropDownList不考虑成员Description上的属性修饰enum.但是,通过查看源代码:

枚举下拉列表助手:https: //aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/Html/SelectExtensions.cs

Enum Helper类:https: //aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/Html/EnumHelper.cs

上面的枚举助手类用于将Enuma 转换为a List<SelectListItem>.从下面的代码:

// Return non-empty name specified in a [Display] attribute for the given field, if any; field's name otherwise
private static string GetDisplayName(FieldInfo field)
{
    DisplayAttribute display = field.GetCustomAttribute<DisplayAttribute>(inherit: false);
    if (display != null)
    {
        string name = display.GetName();
        if (!String.IsNullOrEmpty(name))
        {
            return name;
        }
    }

    return field.Name;
}
Run Code Online (Sandbox Code Playgroud)

你可以看到,在该方法中GetDisplayName它会检查的存在DisplayAttribute的对enum成员.如果显示属性存在,则将名称设置为DisplayAttribute.GetName()方法的结果.

把它放在一起我们可以修改enum使用DisplayAttribute而不是DescriptionAttributeName属性设置为你想要显示的值.

public enum SearchBy
{
    [Display(Name = "SID/PID")]
    SID = 1,
    [Display(Name = "Name")]
    Name,
    [Display(Name = "Birth Date")]
    DOB,
    [Display(Name = "Cause#")]
    Cause
}
Run Code Online (Sandbox Code Playgroud)

这可以为您提供所需的结果.

在此输入图像描述

希望这可以帮助.


Bry*_*yan 5

我创建了一个帮助类来尝试不同类型的属性。我需要它,因为我使用引导程序与https://github.com/civicsource/enumshttps://silviomoreto.github.io/bootstrap-select/

public static class EnumHelper<T>
    {
        static EnumHelper()
        {
            var enumType = typeof(T);
            if (!enumType.IsEnum) { throw new ArgumentException("Type '" + enumType.Name + "' is not an enum"); }
        }

        public static string GetEnumDescription(T value)
        {
            var fi = typeof(T).GetField(value.ToString());
            var attributes = (DescriptionAttribute[]) fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
            return attributes.Length > 0 ? attributes[0].Description : value.ToString();
        }

        public static IEnumerable<SelectListItem> GetSelectList()
        {
            var groupDictionary = new Dictionary<string, SelectListGroup>();

            var enumType = typeof(T);
            var fields = from field in enumType.GetFields()
                         where field.IsLiteral
                         select field;

            foreach (var field in fields)
            {
                var display = field.GetCustomAttribute<DisplayAttribute>(false);
                var description = field.GetCustomAttribute<DescriptionAttribute>(false);
                var group = field.GetCustomAttribute<CategoryAttribute>(false);

                var text = display?.GetName() ?? display?.GetShortName() ?? display?.GetDescription() ?? display?.GetPrompt() ?? description?.Description ?? field.Name;
                var value = field.Name;
                var groupName = display?.GetGroupName() ?? group?.Category ?? string.Empty;
                if (!groupDictionary.ContainsKey(groupName)) { groupDictionary.Add(groupName, new SelectListGroup { Name = groupName }); }

                yield return new SelectListItem
                {
                    Text = text,
                    Value = value,
                    Group = groupDictionary[groupName],
                };
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

你这样称呼它:

<div class="form-group">
   @Html.LabelFor(model => model.Address.State, htmlAttributes: new { @class = "control-label col-md-2" })
   <div class="col-sm-4">
      @Html.DropDownListFor(model => model.Address.State, EnumHelper<StateProvince>.GetSelectList(), new { @class = "selectpicker show-menu-arrow", data_live_search = "true" })
      @Html.ValidationMessageFor(model => model.Address.State, "", new { @class = "text-danger" })
   </div>
</div>
Run Code Online (Sandbox Code Playgroud)

结果


dus*_*os3 5

如果您正在使用或更新版本,则无需创建辅助类.Net Framework 4.0

您可以将该Display属性与EnumDropDownListFor

public enum SearchBy
{
    [Display(Name = "SID/PID")]
    SID = 1,
    [Display(Name = "Name")]
    Name,
    [Display(Name = "Birth Date")]
    DOB,
    [Display(Name = "Cause#")]
    Cause
}
Run Code Online (Sandbox Code Playgroud)

在您看来:

@Html.EnumDropDownListFor(model => model.SearchBy, "Search By", new { @class = "form-control" })
Run Code Online (Sandbox Code Playgroud)

微软文档:

https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.displayattribute?view=netframework-4.8