开发者

ASP.NET MVC: Using EditorFor() with a default template for enums

I've written an EnumDropDownFor() helper which I want to use in conjunction with EditorFor(). I've only just started using EditorFor() so am a little bit confused about how the template is chosen.

My Enum.cshtml editor template is below:

<div class="editor-label">
    @Html.LabelFor(m => m)
</div>
<div class="editor-field">     
    @Html.EnumDropDownListFor(m => m)
    @Html.ValidationMessageFor(m => m)
</div>

Short of explicitly defining the template to use, is there any way to have a default template whi开发者_JAVA技巧ch is used whenever an Enum is passed in to an EditorFor()?


You may checkout Brad Wilson's blog post about the default templates used in ASP.NET MVC. When you have a model property of type Enum it is the string template that is being rendered. So you could customize this string editor template like this:

~/Views/Shared/EditorTemplates/String.cshtml:

@model object
@if (Model is Enum)
{
    <div class="editor-label">
        @Html.LabelFor(m => m)
    </div>
    <div class="editor-field">     
        @Html.EnumDropDownListFor(m => m)
        @Html.ValidationMessageFor(m => m)
    </div>
}
else
{
    @Html.TextBox(
        "",
        ViewData.TemplateInfo.FormattedModelValue,
        new { @class = "text-box single-line" }
    )
}

and then in your view simply:

@Html.EditorFor(x => x.SomeEnumProperty)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜