.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:

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

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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s