Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 DropDownList not validating with [Required] class field as type int? [duplicate]

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>

enter image description here

like image 757
genxgeek Avatar asked Sep 29 '11 02:09

genxgeek


3 Answers

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.

like image 130
Merenzo Avatar answered Oct 23 '22 10:10

Merenzo


[Required] only works for nullable objects and int cannot be nullable. Try using int? instead of int

like image 3
Panos Avatar answered Oct 23 '22 09:10

Panos


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")
like image 1
Nidhin VS Avatar answered Oct 23 '22 10:10

Nidhin VS