How to create an EditorTemplate template for enumeration?

I have a model with enum

public enum Gender
{
    Male,
    Female,
    Unspecified
}

public class FooClass
{
    public Gender UserGender {set; get;}
}

Since this one Gendercan be used in other classes, I would like to create an EditorTemplate for it and ask the editor in the create / edit view:

@Html.EditorFor(model => model.UserGender)

After that I created a partial view located at Views/Shared/EditorTemplates/Gender.cshtml. In the template, I added something just for testing, for example:

@model TestProject.Models.Entity.Gender
@Html.TextBox("")

or

@model TestProject.Models.Entity.Gender
Hello...

but all I get is an Exception:

The model element passed to the dictionary is null, but this dictionary requires an element with a nonzero model of type "TestProject.Models.Entity.Gender".

Is this how the editor templates work or is it completely disabled?

change

If I delete the template file ( Gender.cshtml), I get the text box as an editor and no exception is thrown.

, Create, . return View();

+4
1

-

@model Nullable<TestProject.Models.Entity.Gender>
@Html.ListBox("lb", Enum.GetValues(typeof(TestProject.Models.Entity.Gender)).Cast<TestProject.Models.Entity.Gender>().Select(i => new SelectListItem() { Text = i.ToString(), Value = i.ToString(), Selected=i==Model }))
+1

All Articles