Any idea why the following dropdownlist won't validate with required field as type int (the "Title" field below)?
[Required] // This works!
[Display(Name = "Name")]
public string Name { get; set; }
[Required] // This doesn't work
[Display(Name = "Title")]
public int TitleId { get; set; }
<div class="editor-label">
@Html.LabelFor(model => model.Name, "Name")
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name, "This can't be blank!")
</div>
<div class="editor-label">
@Html.LabelFor(model => model.TitleId, "Title")
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.TitleId, (SelectList)ViewBag.TitleId, String.Empty)
@Html.ValidationMessageFor(model => model.TitleId)
</div>
According to this work item, client-side validation breaks when the SelectList in the ViewBag uses the same name as the field in question. (i.e. both are TitleId
in your case.)
Try this:
@Html.DropDownListFor(model =>
model.TitleId, (SelectList)ViewBag.TitleIdList, String.Empty)
with your SelectList renamed to TitleIdList
accordingly.
[Required]
only works for nullable objects and int cannot be nullable.
Try using int?
instead of int
Or else try with this. Add the below code in your site.css file
select.input-validation-error {
/*border: 1px solid #e80c4d;*/
/*Other styles*/
}
This will show the drop down border color as red, when it is empty.
And in View page:
@Html.DropDownListFor(model => model.TitleID, Model.TitleIDList, "-- Select --", new { @class = "dropdownlist" }) @Html.ValidationMessageFor(model => model.TitleID, "This can't be blank")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With