Handling null values ​​in dropdowns asp.net MVC

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

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

I would imagine that the generated markup on a custom 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? Will this bind correctly to the base model when it's time to save?

+1


a source to share


2 answers


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



+2


a source


Also, whatever field you bind to must be NULL - in this case either a string or a NULL int.



+1


a source







All Articles