2013-10-02 32 views
2

我們知道,如果我們爲基類型定義模板,那麼該模板也可以用於派生類型(如果沒有其他模板用於覆蓋它)。如何爲MVC 4中的枚舉創建默認編輯器模板?

正如我們不能繼承的Enum,也不enum s被認爲從Enum繼承,所以既不在Views\Shared\EditorTemplatesEnum.cshtml模板不會爲對象的不同的自定義枚舉的屬性活躍,像這樣的:

public enum Role 
{ 
    Admin, 
    User, 
    Guest 
} 

我已經看到了關於這個主題的ASP一些普遍的答案,但如果在MVC 4有關於這個問題的一些改進,我想知道?

PS。我的意思是沒有使用任何明確的模板歸屬(如@Html.EditorFor(model => model.Role, "Enum")[UIHint("Enum")]

PPS。我是MVC的新手,所以我會感謝你的簡單答案。

+0

我有點困惑你問什麼。那麼簡單地爲Enum定義一個編輯器模板,即Enum.cshtml是不夠的? – asymptoticFault

+0

apriori,是不夠... – Serge

+0

你可以舉一個例子,從您的枚舉所需的生成的HTML? –

回答

6

K. Scott Allen對此有一個不錯的article

+0

這正是我正在尋找的,非常感謝! – Serge

0

在MVC 5中,可以將模板添加到視圖 - > Shared-> EditorTemplates包含此代碼:

@model Enum 
@{ 
    var optionLabel = ViewData["optionLabel"] as string; 
    var htmlAttributes = ViewData["htmlAttributes"]; 
} 
@Html.EnumDropDownListFor(m => m, optionLabel, htmlAttributes) 

實例:

@Html.EditorFor(model => model.PropertyType, 
       new { 
         htmlAttributes = new { @class = "form-control" }, 
         optionLabel = "Select" 
        }) 

在MVC 4,不這樣做有EnumDropDownListFor擴展,但你可以滾你自己,這是我以前做過這樣的:

public static MvcHtmlString DropDownListFor<TModel, TEnum> 
    (this HtmlHelper<TModel> htmlHelper, 
    Expression<Func<TModel, TEnum>> expression, 
    string optionLabel = null, object htmlAttributes = null) 
{ 
    //This code is based on the blog - it's finding out if it nullable or not 
    Type metaDataModelType = ModelMetadata 
     .FromLambdaExpression(expression, htmlHelper.ViewData).ModelType; 
    Type enumType = Nullable.GetUnderlyingType(metaDataModelType) ?? metaDataModelType; 

    if (!enumType.IsEnum) 
     throw new ArgumentException("TEnum must be an enumerated type"); 


    IEnumerable<SelectListItem> items = Enum.GetValues(enumType).Cast<TEnum>() 
     .Select(e => new SelectListItem 
       { 
        Text = e.GetDisplayName(), 
        Value = e.ToString(), 
        Selected = e.Equals(ModelMetadata 
        .FromLambdaExpression(expression, htmlHelper.ViewData).Model) 
       }); 

    return htmlHelper.DropDownListFor(
     expression, 
     items, 
     optionLabel, 
     htmlAttributes 
     ); 
} 

個參考:

http://stackoverflow.com/questions/79126/create-generic-method-constraining-t-to-an-enum

http://blogs.msdn.com/b/stuartleeks/archive/2010/05/21/asp-net-mvc-creating-a-dropdownlist-helper-for-enums.aspx

相關問題