1

We know that if we define a template for a base type, that template could serve also for the derived types (if any other template was not used to override it).

As we can't inherit an Enum, nor enums are considered inherited from the Enum, so neither the Enum.cshtml template in the Views\Shared\EditorTemplates will not be active for different custom enum properties of the objects, like this one:

public enum Role
{
    Admin,
    User,
    Guest
}

I already saw some answers on this topic for ASP in general, but I am wondering if in MVC 4 there are some improvements on this subject?

PS. I mean without use any explicit template attribution (like @Html.EditorFor(model => model.Role, "Enum") or [UIHint("Enum")])

PPS. I am novice in MVC, so I'll appreciate your simple answers.

4

3 回答 3

7

K. Scott Allen 对此有一篇很好的文章

于 2013-10-02T16:57:53.587 回答
1

在 MVC 5 中,您可以向 Views->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

于 2017-09-01T09:17:00.013 回答
0

还; 有:

@Html.EnumDropDownListFor(model => model.Role, new { @class = ".." })

角色当然是枚举:)

于 2021-03-31T13:15:19.160 回答