下拉列表绑定到枚举

时间:2017-07-14 04:43:01

标签: asp.net-mvc enums html.dropdownlistfor

我正在使用asp.net mvc。这可能是一个直截了当的。我将下拉列表绑定到枚举,如下所示

@Html.DropDownListFor(m => m.IndicatorGroups, Model.IndicatorGroups.ToSelectList(), new { @id = "ddlIndicatorGroup" })

模型定义如下

public class SearchControlViewModel
{
    ...
    public GlobalEnums.IndicatorGroup IndicatorGroups { get; set; }
    ...

}

ToSelectList 功能定义如下

public static SelectList ToSelectList<TEnum>(this TEnum enumObj) where TEnum : struct, IComparable, IFormattable, IConvertible
    {
        var values = from TEnum e in Enum.GetValues(typeof(TEnum))
                     select new { Id = Convert.ToInt32(e), Name = e.ToString() };
        return new SelectList(values, "Id", "Name", enumObj);
    }

现在我已经为枚举添加了带空格的值,我希望显示这些值而不是带有下划线的&#34;值&#34;

 public enum IndicatorGroup
    {
        [EnumMember(Value = "Include ANY MatchingIndicator")]
        Include_ANY_MatchingIndicator = 1,
        [EnumMember(Value = "Include ALL MatchingIndicator")]
        Include_ALL_MatchingIndicator,
        [EnumMember(Value = "Exclude ANY MatchingIndicator")]
        Exclude_ANY_MatchingIndicator,
        [EnumMember(Value = "Exclude ALL MatchingIndicator")]
        Exclude_ALL_MatchingIndicator
    };

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:0)

在MVC中我们有EnumDropDownListFor,它可以直接与我们的任何枚举绑定,它与DropDownListFor非常相似

示例ex:

public enum Courses
{
    [Display(Name = "ASP.NET")]
    ASPNet,
    [Display(Name = "C# .NET")]
    CSharp,
    [Display(Name = "Java")]
    Java,
    [Display(Name = "Objective C")]
    ObjectiveC,

}

型号:

public class Student
{
    [Key]
    public String StudentId { get; set; }

    [Display(Name="Student Name")]
    public String Student { get; set; }

    [Display(Name = "Languages")]
    public Courses Language { get; set; }


}

在视图中:

<div class="form-group">
    @Html.LabelFor(model => model.Languages, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EnumDropDownListFor(model => model.Languages, htmlAttributes: new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.Languages, "", new { @class = "text-danger" })
    </div>
</div>

有用的linK:http://www.advancesharp.com/blog/1163/mvc-enumdropdownlistfor-bind-with-enum-example

由于

KARTHIK

答案 1 :(得分:0)

由于我的要求很简单所以我更换了字符串。我觉得必须有更好的方法来做同样的事情。

public static SelectList ToSelectList<TEnum>(this TEnum enumObj) where TEnum : struct, IComparable, IFormattable, IConvertible
{
    var values = from TEnum e in Enum.GetValues(typeof(TEnum))
                 select new { Id = Convert.ToInt32(e), Name = e.ToString().Replace('_', ' ') };
    return new SelectList(values, "Id", "Name", enumObj);
}