2017-07-14 59 views
0

我使用的是asp.net mvc。這可能是一個直截了當的。我結合我的下拉列表,枚舉如下Dropdownlist綁定到一個枚舉

@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); 
    } 

現在我已經添加了值的空格來枚舉,我想顯示這些值而不是「值與聯合國derscores「

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 
    }; 

我該如何做到這一點?

+1

在'MVC-5',用['EnumDropDownListFor'](https://msdn.microsoft.com/en-us/library/system.web.mvc.html.selectextensions.enumdropdownlistfor%28v= vs.118%29.aspx)直接綁定enum到dropdownlist。 – mmushtaq

+0

請參閱[這個答案](https://stackoverflow.com/questions/388483/how-do-you-create-a-dropdownlist-from-an-enum-in-asp-net-mvc)(使用'DescriptionAttribute ') –

回答

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); 
} 
0

在MVC中,我們有EnumDropDownListFor,我們可以直接與我們的任何枚舉綁定,這是非常相似的DropDownListFor

樣品前:

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> 

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

感謝

KARTHIK

+0

我正在使用mvc 4.5 – Samra