Enum to Dropdown in MVC 5
I just made a simple test.
You mentioned that you have a nullable
Enum, but for that you need public Titles? Title { get; set; }
and using this Model:
public class TestViewModel
{
[System.ComponentModel.DataAnnotations.Required(ErrorMessage = "Please supply the title.")]
[System.ComponentModel.DataAnnotations.Display(Name = "Title")]
public Title? Title { get; set; }
}
public enum Title
{
Mr = 0,
Mrs = 1,
Miss = 2,
Dr = 3
}
with this ActionResult
public ActionResult Test()
{
var model = new List<Models.TestViewModel>();
model.Add(new TestViewModel() { Title = Title.Miss });
model.Add(new TestViewModel() { Title = Title.Mrs });
model.Add(new TestViewModel() { Title = null });
return View(model);
}
and using a simple HTML
@model List<Models.TestViewModel>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head><title>Test</title></head>
<body>
@for (int i = 1; i <= Model.Count; i++)
{
var title = Model[i-1];
<div>
<h2>Model @i</h2>
@Html.LabelFor(x => title.Title)
@Html.EnumDropDownListFor(x => title.Title)
@Html.EditorFor(x => title.Title)
</div>
}
</body>
</html>
I get this as result:
Which is exactly what to expect... are you missing something from my example?
Try naming your Title property something else, Title seems to be a some sort of reserved keyword.