I working with mvc 5. I am loading data from Database Using ORM and fill a drop down list from the controller, like this.
ViewBag.Country_id = new SelectList(_db.Countries, "Country_id", "Description");
As i wanted an empty field first I am doing this in my HTML.
<div class="form-group">
@Html.LabelFor(model => model.Countries, "Country", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("Country_id", null, htmlAttributes: new { @class = "form-control" }, optionLabel: "Choose a Country")
@Html.ValidationMessageFor(model => model.Country_id, "", new { @class = "text-danger" })
</div>
</div>
The empty choice has a "0" value.
And i wanted to validate the user choose a Country so I add this Validation
[Required,Range(1, int.MaxValue, ErrorMessage = "Error: Must Choose a Country")]
public int Country_id { get; set; }
The Problem is that never get me a Error. Always is "0" and the validation did not occur.
What I a missing?
There are few ways to work with DropDownList. I personally like to use Strongly-Type ViewModel instead of ViewBag.
Screen Shot
Validation message displays when submit button is clicked without selecting Country.
Entity
Model
Controller
View