Doug.Instance

Improving the world one post at a time
posts - 17, comments - 33, trackbacks - 0

My Links

News

Tag Cloud

Archives

Post Categories

My Sites

Problem: DropDownList Always Posts Blank Value in ASP.Net MVC 2

Consider the following code:

<%= Html.DropDownList("State", new SelectList(new string[] { "","AK","AL","AR","AS","AZ","CA","CO","CT","DC","DE","FL","GA","GU","HI","IA","ID",
                    "IL","IN","KS","KY","LA","MA","MD","ME","MH","MI","MN","MO","MS","MT","NC","ND","NE","NH","NJ","NM","NV","NY",
                    "OH","OK","OR","PA","PR","PW","RI","SC","SD","TN","TX","UT","VA","VI","VT","WA","WI","WV","WY"})) %>

Simple enough, right?  Display a dropdown list with a value for each state.  There is only one problem.  The resulting HTML looks like this:

<select id="State" name="state"><option></option><option>AK</option>...

While this is valid HTML in most browsers, it fails in IE 8 running in compatability mode.  In essence, it is treated like this:

<option value=""></option><option value="">AK</option>...

A simple solution is to force a value like this:

<%= Html.DropDownList("State", new SelectList((new string[] { "","AK","AL","AR","AS","AZ","CA","CO","CT","DC","DE","FL","GA","GU","HI","IA","ID",
                    "IL","IN","KS","KY","LA","MA","MD","ME","MH","MI","MN","MO","MS","MT","NC","ND","NE","NH","NJ","NM","NV","NY",
                    "OH","OK","OR","PA","PR","PW","RI","SC","SD","TN","TX","UT","VA","VI","VT","WA","WI","WV","WY"}).Select(x => new { Text = x, Value = x}), "Value", "Text", null)) %>

You're welcome!

Print | posted on Tuesday, February 07, 2012 10:08 AM | Filed Under [ MVC ]

Feedback

No comments posted yet.
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: