2015-04-13 20 views
7

Tôi mới dùng asp.net MVC. Tôi đang cố gắng sử dụng kiểm soát thả xuống trên trang xem của tôi, mà populates từ enum. Tôi cũng muốn thêm mô tả tùy chỉnh vào các giá trị thả xuống. Tôi đã tìm kiếm rất nhiều ví dụ, nhưng không ai đăng tải cách mô tả trên trang xem. Đây là mã của tôi:cách sử dụng enum với DescriptionAttribute trong asp.net mvc

ViewModel:

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

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> 

Nó không phải là populating với các lĩnh vực mô tả như đã đề cập trong enum SearchBy tôi. xem hình ảnh ở đây. http://postimg.org/image/phdxgocj7/ Hãy giúp tôi, nơi tôi đang phạm sai lầm. Cảm ơn bạn

CẬP NHẬT: Tôi đã nhận được giải pháp cho việc này từ Nico. Và tôi đã nghiên cứu một chút về điều này. Tôi đang cập nhật bài đăng này bằng giải pháp vì nó có thể hữu ích cho những người khác, những người mới làm quen với MVC http://weblogs.asp.net/jongalloway//looking-at-asp-net-mvc-5-1-and-web-api-2-1-part-1-overview-and-enums

Cảm ơn tất cả. Tận hưởng mã hóa ..

+0

Không có EnumDropDownListFor() 'phương pháp 'trong MVC -4. Bạn có nghĩa là MVC-5 hoặc là một trợ giúp tùy chỉnh? –

+0

Rất tiếc, tôi đã cập nhật thẻ. Có, tôi đang sử dụng MVC-5 –

Trả lời

16

Trình trợ giúp Html EnumDropDownListFor hoặc EnumDropDownList không tính đến trang trí thuộc tính Description thuộc các thành viên enum. Tuy nhiên bằng cách xem mã nguồn:

Enum Dropdown Danh sách Helper: https://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/Html/SelectExtensions.cs

Enum Helper Lớp học: https://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/Html/EnumHelper.cs

Các enum lớp helper trên được sử dụng để chuyển đổi một Enum đến một List<SelectListItem>. Từ đoạn code dưới đây:

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

Bạn có thể thấy rằng trong phương pháp GetDisplayName nó kiểm tra sự tồn tại của DisplayAttribute trên enum thành viên. Nếu thuộc tính hiển thị tồn tại thì tên được đặt thành kết quả của phương thức DisplayAttribute.GetName().

Đặt chúng lại với nhau, chúng tôi có thể sửa đổi enum để sử dụng DisplayAttribute thay vì DescriptionAttribute và đặt thuộc tính Name thành giá trị bạn muốn hiển thị.

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

Điều này mang đến cho bạn kết quả mong muốn.

enter image description here

Hy vọng điều này sẽ hữu ích.

+0

Cảm ơn bạn Nico. Điều này giúp, nhưng trong trang xem, những gì tôi nên thay thế EnumDropDownListFor với? –

+0

Sau một chút nghiên cứu, tôi hiểu rằng, tôi phải viết mẫu Hiển thị để hiển thị Enum đúng cách để xem dưới dạng menu thả xuống, đúng không? đúng nếu tôi đã sai lầm. Tôi tìm thấy một bài viết về điều này ở đây: http://www.codeproject.com/Articles/776908/Dealing-with-Enum-in-MVC –

1

Given:

public enum MyEnum 
{ 
    [Description("This is the description if my member A")] 
    A, 
    [Description("This is the description if my member B")] 
    B 
} 

Cá nhân tôi sử dụng phương pháp mở rộng này để có được một mô tả từ enum của tôi:

public static string GetDescription(this Enum value) 
     { 
      FieldInfo fi = value.GetType().GetField(value.ToString()); 

      DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false); 

      if (attributes != null && attributes.Length > 0) 
      { 
       return attributes[0].Description; 
      } 
      else 
      { 
       return value.ToString(); 
      } 
     } 

Để sử dụng nó:

MyEnum.A.GetDescription(); 

Hope trợ giúp này.

+0

Cảm ơn bạn Andrew. Nico đã giúp tôi giải quyết vấn đề. –

0

Tôi đã tạo một lớp trợ giúp thử các loại thuộc tính khác nhau. Tôi cần nó vì tôi đã sử dụng bootstrap với 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], 
       }; 
      } 
     } 
    } 

Và bạn gọi nó thích:

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

Result

Các vấn đề liên quan