C# ASP.Net MVC Editor Templates

Editor templates are used in ASP.Net to provide a standard html snippet for a model that can be accessed via the static html helper class @Html.EditorFor().

As with a lot of ASP.Net, there's some convention with Editor templates that has to be observed to get them working in your project:
1. Make sure they can be found in /Views/Shared/EditorTemplates/...
2. The template name must match the type eg: DateTime.cshtml

Using Nullable Enum editor
If you're passing a nullable object to an editor template, then it's not possible to query the type of the Enum eg: var modelType = Model.GetType().

So how do you create a generic enum editor template that supports nullable enums?

@model Enum
@{
    var type = Nullable.GetUnderlyingType(ViewData.ModelMetadata.ModelType)
               ?? ViewData.ModelMetadata.ModelType;
}

<div class="enum">
    <div class="btn-group btn-group-justified">
        @Html.HiddenFor(m => m, new { @class="group validate" })
        @foreach (Enum value in Enum.GetValues(type))
        {
            <div class="btn-group" role="group">
                <button type="button" class="btn @(Equals(Model, value) ?
                   "btn-default btn-primary" :
                   "btn-default")" data-value="@value">
                        @value.GetDisplayName()
                </button>
            </div>
        }
    </div>
</div>

By using the ModelMetadata and Nullable.GetUnderlyingType, we're able to get a Type even when the model value is null.

The above editor template is based on using bootstrap css, and generates an inline list of buttons for any given Enum, where the button is btn-primary if the value is selected.