2

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.

push 22
  • 1,172
  • 3
  • 15
  • 34

2 Answers2

2

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.

suhair
  • 10,895
  • 11
  • 52
  • 63
0

First, if a dropdown is required, add the [Required] attribute to your model property.

Then, enable client side validation somewhere at the top of your view:

<% Html.EnableClientValidation() %>

Then add

@Html.ValidationMessage("S", "*")

Above will only work if the 'default' selection has a null or empty value. Also ensure you've got the correct js files referenced in the script tags at the top of your page

heads5150
  • 7,263
  • 3
  • 26
  • 34
  • in msvc3 EnableClientValidation and UnobstrusiveJacascriptEnabled is set in the Web.config by default. – push 22 Apr 28 '11 at 13:54