Select Page
This entry has been published on 2016-06-13 and may be out of date.

Last Updated on 2016-06-13.

[:en]Scenario

In your SQL database table, you have e.g. a foreign key relation – a nullable column of one table references another table which contains the items for your DropDownList (HTML Select).

But by default, Html.DropDownListFor() does not have an option for the user to choose the NULL value.

Solution

Add a NULL option to your list before you call DropDownListFor().

In your View:

<div class="dropdown">
    Example
    @{
          var list = new SelectList(ViewBag.list, "name", "name_friendly", "(none)").ToList();
          list.Insert(0, new SelectListItem() { Value = null, Text = "(none)" });
     }
     @Html.DropDownListFor(yourFkTable => yourFkTable.chosenItem, list)
</div>

UPDATE 2016-07-16:

The above solution might case controller validation errors.

But there is a much easier way.

<div class="dropdown">
    Example
        @Html.DropDownListFor(yourFkTable => yourFkTable.chosenItem, list, "(none)")
</div>

If the third parameter is given, “(none)” will be converted into “<option value=””>“, which is accepted by your controller.

Also make sure your SQL column value allows null values.

Reference[:]