Validate static dropdown in MVC5

1.4k views Asked by At

I have on drop down.

Model

 [Required(ErrorMessage = "Please selectvehicle")]
        public string VehicleRequested { get; set; }

index.cshtml

   @Html.DropDownList("VehicleRequested", new List<SelectListItem>

                 {
                    new SelectListItem{ Text="Active", Value = "1" },
                    new SelectListItem{ Text="Not-Active", Value = "0" }
                 })
                    @Html.ValidationMessageFor(model => model.VehicleRequested)

I cannot see the required feild validation append, M i wrong any where , please suggst

2

There are 2 answers

0
AudioBubble On BEST ANSWER

Your dropdownlist only has 2 items, one with value="0", the other with value="1" Both "0" and "1" are valid strings (neither are null) so validation always passes. Your property can never be invalid so you never get a validation error.

Its not really clear why your binding a int value to string property, and the fact you display only 2 values ("Active" and "Not-Active") suggests you property really should be a bool.

If you want to add an option such as "-please select-" that results in a validation error if one of the other 2 options is not selected, then use the overload that accepts optionLabel

@Html.DropDownList("VehicleRequested", new List<SelectListItem>
{
    new SelectListItem{ Text="Active", Value = "1" },
    new SelectListItem{ Text="Not-Active", Value = "0" }
}, "-Please select-")
@Html.ValidationMessageFor(model => model.VehicleRequested)

This will add the first option as <option value>-Please select-</option>. Note that the value attribute does not have a value, so if its selected when you submit, VehicleRequested will be null and you will see the error message.

Side note: Suggest you use the strongly typed helper - @Html.DropDownListFor(m => m.VehicleRequested, ...) and that you build the your Selectist in the controller and pass it to the view as a ViewBag or (better) a view model property.

0
Kaf On

Use @Html.DropDownListFor()

@Html.DropDownListFor((model => model.VehicleRequested, new List<SelectListItem>

             {
                new SelectListItem{ Text="Active", Value = "1" },
                new SelectListItem{ Text="Not-Active", Value = "0" }
             })