tags:

views:

130

answers:

2

How do I create a dropdown in ASP.NET MVC that can handle a null value?

The application is a lookup field in a database, where the primary key is in a lookup table, i.e. Categories, and the foreign key is in another table, i.e. CategoryID, but CategoryID is OPTIONAL (i.e. it can contain a null).

I would imagine the generated markup in the user's web page would look something like this:

<select id="foo">
    <option value="">(Not Specified)</option>
    <option value="1">Alpha</option>
    <option value="2">Bravo</option>
    <option value="3">Charlie</option>
</select>

Can I do something like this without having to write a custom HtmlHelper? Would this bind properly to the underlying model when the time comes to save?

+2  A: 

You don't need to write a helper. It already exists. Use one of the Html.Select overloads which takes an optionLabel argument. Set that to "(Not Specified)".

Craig Stuntz
That was too simple. :)I guess I didn't grok the intellisense...it says, "Provides the text for a default empty valued option, if it is not null." That would have no meaning to me at all if I didn't have a good understanding of markup, although if that were the case I probably shouldn't be playing in the MVC sandbox anyway. Also, the phrase "if it is not null" seems backwards.Anyway, thanks for the help. Sometime one just needs to ask.
Robert Harvey
I assume it is referring to the option label when it states "if it is not null". The way this seems to work is, if you specify null (or another overload that doesn't set it) it does not show the blank option at all. Otherwise, whatever you specify - including an empty string, which is not null - is used as the blank option text.
GalacticCowboy
Yeah, the description could be better, there.
Craig Stuntz
+1  A: 

Also, whatever field you are binding to must be nullable - in this case, either a string, or a nullable int.

GalacticCowboy