Search code examples
asp.net-mvc-3client-side-validation

ASP MVC 3: How can I do Client side Validation on a Select List?


After reading a few question/answers here I have managed to work out how to add a Select list to a form and fill it with data, like so:

@Html.DropDownList("S", new SelectList(ViewBag.S, "Id", "Nme"), "-- Sel a S --")

And it works perfectly. However I would like to add some client-side Validation To validate whether the user has selected an option and not left it at the Default.

I'm using the standard jquery stuff that comes with mvc 3, so presumably I have to do something with HTML.ValidationMessage, but what?

And Can't for the life of me work out how.

TIA.

Ok I had a look through how its done in JQuery land and found just by adding an htmlattribute like so:

new {@class='required'}

to my Html.DropDownList statement, and adding validationMessage, fixes the problem for me.


Solution

  • If you are using the jquery validation then you may simply add the css class reuired and have the required validation for the dropdownlist, provided the default value is empty.