如何在MVC 4中为枚举创建默认编辑器模板?
我们知道,如果我们为基类型定义模板,那么该模板也可以用于派生类型(如果没有使用任何其他模板来覆盖它)。
由于我们无法inheritanceEnum
,因此Enum
也不会被认为是从Enum
inheritance的,因此Views\Shared\EditorTemplates
的Enum.cshtml
模板都不Enum.cshtml
对象的不同自定义枚举属性有效,如下所示:
public enum Role { Admin, User, Guest }
我已经在ASP中看到了关于这个主题的一些答案,但是我想知道在MVC 4中是否对这个主题有一些改进?
PS。 我的意思是不使用任何明确的模板属性(如@Html.EditorFor(model => model.Role, "Enum")
或[UIHint("Enum")]
)
PPS。 我是MVC的新手,所以我很感激你的简单答案。
K. Scott Allen有一篇很好的文章 。
在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 (this HtmlHelper htmlHelper, Expression> 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 items = Enum.GetValues(enumType).Cast() .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