Using MVC3 with NHibernate, I am having a problem with dropdowns. I have a form with various fields for user input and am only having trouble with a particular select element.
My problem is that the value of a property of the model is not shown as selected when the view loads even though the model is bound and saves properly on post. What makes this strange is that the MainPopulationFocus (code snippets below) dropdown works correctly while the MilitaryService dropdown does not.
Model – declaration of properties in question
public virtual System.Int32? MilitaryService { get; set; }
public virtual System.Int32? MainPopulationFocus { get; set; }
View – military service label and dropdown
@Html.LabelFor( m => m.MilitaryService, "Military Service" )
@Html.DropDownListFor(m => m.MilitaryService, ViewBag.MilitaryService as IQueryable<SelectListItem>, "", new { style = "width: 140px" })
HTML
<label for="MilitaryService">Military Service</label>
<select id="MilitaryService" name="MilitaryService" style="width: 140px">
<option value=""></option>
<option value="1028">Active</option>
<option value="1029">Reserve</option>
<option value="1030">National Guard</option>
<option value="1031">Retired Military</option>
</select>
Same View – main population focus label and dropdown
@Html.LabelFor( m => m.MainPopulationFocus, "Main Population Focus" )
@Html.DropDownListFor(m => m.MainPopulationFocus, ViewBag.MainPopulationFocuses as IQueryable<SelectListItem>, "", new { style = "width: 140px" })
HTML
<label for="MainPopulationFocus">Main Population Focus</label>
<select data-val="true" data-val-number="The field MainPopulationFocus must be a number." id="MainPopulationFocus" name="MainPopulationFocus" style="width: 140px">
<option value=""></option>
<option value="808">Education</option>
<option value="809">Policy</option>
<option selected="selected" value="810">Clinical Practice</option>
<option value="811">Research</option>
</select>
Controller – Get list of objects from service layer and save List to ViewBag
.Select(s => new SelectListItem() { Text = s.Display, Value = s.ID.ToString(), Selected = (s.ID == fellowsProfile.MilitaryService) });
The MainPopulationFocus dropdown works perfectly while the MilitaryService dropdown value chosen is bound to the model and saves in the DB but does not show the value selected when the view loads.
I know that there is an issue that exists when you use the same name for the model and dropdown but I have avoided that. I think it probably has to do with the way I formed the List.
Thanks for any possible help/suggestions.
Discovered I did use the same name and that is why I was getting my issue. Using ViewBag.MilitaryService along with the model property of MilitaryService is what broke the use of the dropdown list.