Blog Home  Home Feed your aggregator (RSS 2.0)  
.Net Jonesie - MVC DropDownList and blank options
A simple programmers blog
 
# Thursday, January 15, 2009
I'm loving MVC.  In fact, it is my new love.  SharePoint is out - that was a bad relationship anyway - too sadistic.

There are however, a few things in the current beta that require a workaround or two.  Here's one.

To create a dropdown list in MVC you use the HtmlHelper thus:

<%= Html.DropDownList("CityID") %>

then in your controller you add the following before calling the view:

ViewData["CityID"] = new SelectList(from c in someDataContext.Cities orderby c.Name select c, 
"CityID","Name", selectedCityID);

where selectedCityID is the item you want preselected in the list.  Note that the ViewData key and the control name all match.  And this just works.  Easy as cake.

But now, suppose you want an option at the top of the list such as "[select a city]" when you are adding new records.  Again, this is a peice of pie, just do this :

<%= Html.DropDownList("[select a city]", "CityID") %>

The dropdown list will now contain this extra option at the top of the list of city, and it's value will be blank.

BUT..  the specified selectedvalue of selectedCityID will not be selected any more.  If you look a the page source generated by the HtmlHelper you will see that none of the options has selected=selected.

I dont know if this is a bug and/or if it will be fixed by the release candidate (due any day) but as a workaround I have used the following jQuery code to pre-select the default option:

$(function() {
  $("select[@name='CityID'] option[@value='<%= ViewData.Model.CityID%>']").attr('selected', 'selected');
});

Hope this helps someone else :)

Thursday, January 15, 2009 9:34:24 AM (New Zealand Daylight Time, UTC+13:00)  #    Comments [3]   General  | 
Friday, January 23, 2009 1:44:44 AM (New Zealand Daylight Time, UTC+13:00)
solved my problem thanks
Rod Connors
Tuesday, February 24, 2009 6:01:02 AM (New Zealand Daylight Time, UTC+13:00)
Thank you! That's exactly the jQuery snippet that I was looking for.
Thursday, May 07, 2009 12:55:40 AM (New Zealand Standard Time, UTC+12:00)
thanks you for this useful article
Comments are closed.
Copyright © 2012 Peter G Jones. All rights reserved.
DasBlog 'Portal' theme by Johnny Hughes.
Pick a theme: