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

两盒软妹~` 提交于 2019-12-24 03:30:36

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/5818862/asp-mvc-3-how-can-i-do-client-side-validation-on-a-select-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!