How can I create an EditorTemplate for an enum?

378 views Asked by At

I have a model with an enum

public enum Gender
{
    Male,
    Female,
    Unspecified
}

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

Since this Gender might be used in other classes, I wanted to create an EditorTemplate for it and ask for an editor in the create/edit view:

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

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

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

or

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

but all I get is an Exception:

The model item passed into the dictionary is null, but this dictionary requires a non-null model item of type 'TestProject.Models.Entity.Gender'.

Is this how Editor Templates work or I'm completely off track?

edit:

If I delete the template file (Gender.cshtml) I am getting a textfield as editor, and no exception is thrown.

Also, this is for a Create view and in the controller I pass no object to it. I just call return View();

1

There are 1 answers

0
Grundy On BEST ANSWER

you can try something like this

@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 }))