Question

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();

Was it helpful?

Solution

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 }))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top