18

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 which is used whenever an Enum is passed in to an EditorFor()?

ajbeaven
  • 9,265
  • 13
  • 76
  • 121

1 Answers1

25

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)
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Excellent! Had read that post but didn't realise that string would be used by default. Is this the template that is used if it can't match anything else? – ajbeaven Apr 16 '11 at 09:38
  • 1
    Cannt get it to work, as @if(Model is Enum) always return false as the Model is alwyes null!! .. what I'm missing!! ... thanks alot. – Hossam May 31 '11 at 18:27
  • 1
    `@if(ViewData.ModelMetadata.ModelType.IsEnum)` should be used instead of checking the instance, so that nullabes are picked up correctly. – Ivan Zlatev Dec 03 '12 at 16:06
  • 3
    Guh I meant to say `ViewData.ModelMetadata.ModelType`, because if it's nullable IsEnum will return false so you have to check the underlying type. – Ivan Zlatev Dec 03 '12 at 16:51