Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make @Html.DropDownList() allow null

I've used Visual Studio to automatically generate Controllers and Views from a database. In the database, there's a table dbo.Items, which has a FOREIGN KEY (CategoryID) REFERENCES Categories(Id)

The generated View for Items/Create has this block, which forces users to select 01 Category from a drop-down list when adding a new Item, no null value allowed:

    <div class="form-group">
        @Html.LabelFor(model => model.CategoryID, "CategoryID", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("CategoryID", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.CategoryID, "", new { @class = "text-danger" })
        </div>
    </div>

How do I make the Null option available?

like image 533
Vu TrongNghia Avatar asked Oct 24 '17 00:10

Vu TrongNghia


1 Answers

Html.DropDownList() is an html helper method which will generate the HTML markup for rendering a SELECT element. It does not do any "allow/not allow" thing by itself.

MVC model validation framework does the model validation on the server side when you submit the form based on your view model properties and the data annotations defined on that. The helper method also generates the needed data attributes which the jQuery validate plugin can use to do client side validation.

To allow selecting no options in the SELECT element change the CategoryID property to nullable int. If you have a view model, you may udpate there.

public class YourViewmodel
{
  public int? CategoryID { set;get;}
}

You need to update your db schema as well to save nullable value in the CategoryId column. If you are using database first approach, you can make the db schema change (changing the column to nullable) and then regenerate the entity classes.

I also suggest you using the DropDownListFor helper

@Html.DropDownListFor(x=>x.CategoryID,ViewBag.CountryCode as  List<SelectListItem>,
                                       "select one", new { @class = "form-control" })

Assuming ViewBag.CountryCode is a list of SelectListItem's you set in your GET action method.

like image 177
Shyju Avatar answered Oct 05 '22 22:10

Shyju