I am experiencing inconsistent issues with ASP.Net MVC4's implementation of DropDownListFor.
In my ViewModel I have two string properties Title and EmploymentStatus which have data annotations to validate the model. When the ModelState.IsValid is false and the user is sent back to my input form the Title drop down list defaults to the first item in the list and not the value tied to the ViewModel. However, the EmploymentStatus drop down is behaving as expected, and I can't easily see the difference.
My ViewModel contains the following properties:
[Display(Name = "Title")]
[RegularExpression("^omitted$", ErrorMessage="Please enter a title")]
public String Title
{
get;
set;
}
[Display(Name = "Employment status?")]
[RegularExpression("^omitted$", ErrorMessage = "Please enter your employment status")]
public String EmploymentStatus
{
get;
set;
}
My View contains the following two lines to render the drop down lists:
@Html.DropDownListFor(m => m.Title, new SelectList(LookupService.GetTitleLookup(),"Key","Value", Model.Title)
@Html.DropDownListFor(m => m.EmploymentStatus, new SelectList(LookupService.GetEmploymentStatusLookup(),"Key","Value", Model.EmploymentStatus))
The LookupService methods both return an object of Dictionary: e.g.
- "Mr", "Mr"
- "Mrs", "Mrs"
etc
"F", "Full Time"
- "P", "Part Time"
- etc
As part of the SelectList constructor it allows you to set the SelectedValue (in my case Model.Title) which when debugging I have stepped through and confirmed that the Model value was valid.
There are many people who seem to having issues with DropDownListFor not displaying the selectedValue and it appears that occasionally the internal implementation uses the default value rather than the selected value passed in, and that it doesn't support indexed properties, neither seem to be applicable in my case.
Any help would be greatly appreciated. Thanks