2

如何客户端验证下拉列表框.....

            @Html.DropDownListFor(per => per.Gender, new[] {
                        new SelectListItem(){Text = "Male" , Value="Male"},
                        new SelectListItem(){Text ="Female" , Value = "Female"},
                    }, "Select Your Gender")
            @Html.ValidationMessageFor(per => per.Gender)
4

1 回答 1

1

在您的视图中包含 jquery 验证插件脚本以及 jQuery(如果尚未在 Layout.cshtml 中引用)

@model SomeModel
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>    
@using (Html.BeginForm())
{

   @Html.DropDownListFor(per => per.Gender, new[] {
                        new SelectListItem(){Text = "Male" , Value="Male"},
                        new SelectListItem(){Text ="Female" , Value = "Female"},
                    }, "Select Your Gender")
            @Html.ValidationMessageFor(per => per.Gender)

    <input type="submit" />
}

并确保 SomeModel 的 Gender 属性是必需的

[Required]
public string Gender { set;get;}

更新您web.config并将调用的 AppSetting 设置ClientValidationEnabled为 true

<appSettings>
  <add key="ClientValidationEnabled" value="true" />
  <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

现在,当您提交时,如果在浏览器中启用了 javascript,它将执行客户端验证。

于 2012-07-26T15:45:50.423 回答