繁体   English   中英

如何在@Html.DropDownListFor 中为枚举 class 中的属性显示不同的名称

[英]How to display different name for properties in enum class in @Html.DropDownListFor

假设我有 model:

using System.ComponentModel.DataAnnotations;

namespace MyProject.Models
{
   public class InputParametersModel
   {        
      public Variable Xvariable { get; set; }

      public Variable Yvariable { get; set; }
   }

    public enum Variable
    {
        [Display(Name = "A A")]
        aa,
        [Display(Name = "B B")]
        bb,
        [Display(Name = "C C")]
        cc,
    }
}

我的观点是:

@model MyProject.Models.InputParametersModel
@using MyProject.Models

<div>
@using (Html.BeginForm())
{
@Html.DropDownListFor(m => m.Xvariable, new SelectList(Enum.GetValues(typeof(Variable))), "Select", new { @class = "form-control"})
@Html.DropDownListFor(m => m.Yvariable, new SelectList(Enum.GetValues(typeof(Variable))), "Select", new { @class = "form-control"})
}
</div>

如何让下拉菜单显示“AA”、“BB”和“CC”? 我认为添加[Display(Name = "AA")]可以解决我的问题,但它仍然显示 'aa' 等。

(这只是代码的一个片段,但希望我解释了任何语法错误)

编辑:忘记复制@using (Html.BeginForm())

您可以使用Html.GetEnumSelectList in.Net Core 显示显示名称

@Html.DropDownListFor(m => m.Xvariable,Html.GetEnumSelectList<Variable>(),
                                    new { @class = "form-control" })

//Or

<select asp-for="Xvariable" asp-items="Html.GetEnumSelectList<Variable>()">
     <option selected="selected" value="">Please select</option>
</select>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM