Creating a Null Option in a DropDownList

When scaffolding out views for an entity that is linked to another object Visual Studio will create a drop down list of the values in the linked table so that users can select an option from the list rather than enter some arbitrary and usually unknown ID number. The only problem with this is what if that field can accepts null values. This is not coded into the template by default. For example, in the Items table we have a CategoryId field that allows nulls.

When we scaffold this entity the create form populates that drop down list with the values from the table but even through the column allows nulls because of the drop down we are required to select an option.

All we need to do to enable this ability is add one additional attribute to the Html.DropDownList help as shown below.

By adding the addition of the “– Categories –” option this value is shown as the first option in the drop down list.

When selected this will send a null value to be entered into the Items table for the CategoryId column.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *