2011-12-08 28 views
1

我知道這個主題有幾個線程。我看到很多解決方案,但大多數都需要知道枚舉類型。由於默認情況下,Enum使用字符串模板,因此找出確切類型更加困難。MVC 3:用於EditorForModel的枚舉下拉模板

有人得到了一個完整的例子,如何解決這個問題?

編輯。基於Roys的建議,這是我的代碼。

HtmlHelpers.cs

public static MvcHtmlString EnumDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) where TModel : class 
{ 
    var type = htmlHelper.ViewData.ModelMetadata.ModelType; 
    var inputName = type.Name; 
    var value = htmlHelper.ViewData.Model == null ? default(TProperty) : expression.Compile()(htmlHelper.ViewData.Model); 
    var selected = value == null ? String.Empty : value.ToString(); 
    return htmlHelper.DropDownList(inputName, ToSelectList(type, selected)); 
} 

private static IEnumerable<SelectListItem> ToSelectList(Type enumType, string selectedItem) 
{ 
    var items = new List<SelectListItem>(); 
    foreach (var item in Enum.GetValues(enumType)) 
    { 
     var fi = enumType.GetField(item.ToString()); 
     var attribute = fi.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault(); 
     var title = attribute == null ? item.ToString() : ((DescriptionAttribute)attribute).Description; 
     var listItem = new SelectListItem 
     { 
      Value = ((int)item).ToString(), 
      Text = title, 
      Selected = selectedItem == ((int)item).ToString() 
     }; 
     items.Add(listItem); 
    } 

    return new SelectList(items, "Value", "Text"); 
} 

視圖模型

public class AddTestForm 
{ 
    [UIHint("Enum")] 
    public EnumType Type { get; set; } 

    public string Description { get; set; } 

public enum EnumType 
{ 
    One = 1, 
    Two = 2 
} 

EditorTemplates/Enum.cshtml

@model object 

@Html.EnumDropDownListFor(x => x) 

而在意見...

@Html.EditorForModel() 

現在的問題是,我不能枚舉填寫表格已經發布之後。

+0

檢查這一個:http://stackoverflow.com/questions/4656758/mvc3-razor-dropdownlistfor-enums –

+0

我更新了我的答案。也許你看到明顯的東西。 –

回答

2

你的幫手產生錯誤的名稱來生成select元素:

<select id="Type_EnumType" name="Type.EnumType"> 

DefaultModelBinder使用name屬性相匹配的屬性名稱。您的助手生成名稱"Type.EnumType"與Model屬性名稱不匹配。要使其工作而不是類型名稱,您需要從表達式中獲取屬性名稱。這是與ExpressionHelper類很簡單:

public static MvcHtmlString EnumDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) where TModel : class 
{ 
    ... 
    return htmlHelper.DropDownList(ExpressionHelper.GetExpressionText(expression), ToSelectList(type, selected)); 
}