4.06.2011

.NET MVC DropDownList, SelectList and Selected Value

If you've tried using the Html.DropDownList in .NET MVC you know that it the selectedValue of the populating SelectList doesn't work. The frequently posted workaround, is to change the name of DropDownList to something other that the field it is supposed to be bound to.

Perfect, now the value is selected in the list as expected. BUT, the problem with this however is that is the DropDownList no longer binds to the model as needed. Since we've changed the name, updates to the database do not work. After reading numerous posts on Stackoverflow I discovered zero solutions.

Here is how I resolved it:

Assuming that your SelectList is constructed in your Controller or ViewModel like this:

CatsRepository CatsRepo = new CatsRepository();
CatsList = new SelectList(CatsRepo.FindCats(), "CatId", "Category", Content.CatId);


The HTML.DropDownList can be constructed in your control like this:


%lt;input type="hidden" name="CatId" id="CatId" value="" /%gt;
%lt;%= Html.DropDownList("CatIdList", Model.CatsList, new { @onchange = "CatId.value = this.value"})%%gt;

In Summary,

1) I renamed my "CatId" bound DropDownList to "CatIdList".
2) Then I added a hiddel field named "CatId" setting it's value to "".
3) I added a "new { @onchange = "CatId.value = this.value"}" as an htmlAttribute to my DropDownList, so when a different value is picked it updates the hidden field value accordingly.