Search code examples
c#asp.net-mvcasp.net-mvc-5html-helper

Enum to Dropdown in MVC 5


I have a nullable enum defined for a person title and used in a person model.

public enum Titles
{
    Mr=0,
    Mrs=1,
    Miss=2,
    Dr=3
}
[Required(ErrorMessage="Please supply the title.")]
[Display(Name = "Title")]
public Titles Title { get; set; }

When I add this property into a create or edit view using the HTML Helper

@Html.EnumDropDownListFor(model => model.Title)

the control renders as expected with the enum values within it.

However, when I choose to edit an existing person, the title enum doesn't show the current title. It shows an empty entry at the top of the DropDownList.

However, if I remove the nullable, it always shows the first item in the enum.

Any ideas how I get the DropDownList to display the correctly chosen enum item for the person I am editing?

Many thanks,

Jason.


Solution

  • Try naming your Title property something else, Title seems to be a some sort of reserved keyword.