Reputation: 140
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?
Upvotes: 5
Views: 6155
Reputation: 51
We need to set a List object explicitly and pass it into the Html.DropdownList() like this,
@{
List<SelectListItem> selectList = new List<SelectListItem>();
selectList.Add(new SelectListItem
{
Text = "select option",
Value = ""
});
}
@Html.DropDownListFor(model => model.CategoryID, selectList, new { @class="form-control" })
Upvotes: 0
Reputation: 407
You can use fallowing overloaded version to show "select option" initially...
@Html.DropDownList("CategoryID", null, "select option", new { @class = "form-control" })
and whenever you are adding options to the CategoryID dropdown, you need to add "select option" as first one and rest after that...
Upvotes: 2
Reputation: 218942
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.
Upvotes: 3