Mig*_*tom 6 validation client asp.net-mvc-3
我的模型上有一个必需的注释:
[Required(ErrorMessage = "Please choose an option")]
public bool? AnyDebts { get; set; }
Run Code Online (Sandbox Code Playgroud)
我在web.config中启用了客户端验证:
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
Run Code Online (Sandbox Code Playgroud)
我在我的布局中引用了jquery脚本:
<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-1.4.4.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.6.custom.min.js")" type="text/javascript"></script>
Run Code Online (Sandbox Code Playgroud)
我还需要做些什么才能使客户端验证工作?服务器端验证仍然有效.
编辑:
啊哈!
我发现客户端验证工作正常.
但是,具体来说,我发现模型属性未经过验证,客户端是那些使用自定义属性注释的属性.例如:
[BooleanRequiredToBeTrue(ErrorMessage = "You must agree to the statements listed")]
public bool StatementAgree { get; set; }
Run Code Online (Sandbox Code Playgroud)
属性的代码:
public class BooleanRequiredToBeTrueAttribute: RequiredAttribute
{
public override bool IsValid(object value)
{
return value != null && (bool)value;
}
}
Run Code Online (Sandbox Code Playgroud)
这些未经验证的客户端是否已经存在?
<script src="@Url.Content("~/Scripts/jquery-1.4.4.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
Run Code Online (Sandbox Code Playgroud)
是客户端验证工作所需的唯一脚本.
和往常一样,这是一个完整的工作演示:
模型:
public class MyViewModel
{
[Required(ErrorMessage = "Please choose an option")]
public bool? AnyDebts { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel());
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
Run Code Online (Sandbox Code Playgroud)
视图:
@model AppName.Models.MyViewModel
@{
ViewBag.Title = "Home Page";
}
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
@using (Html.BeginForm())
{
<div>Debts</div>
<span>Yes</span> @Html.RadioButtonFor(x => x.AnyDebts, true)
<span>No</span> @Html.RadioButtonFor(x => x.AnyDebts, false)
@Html.ValidationMessageFor(x => x.AnyDebts)
<input type="submit" value="OK" />
}
Run Code Online (Sandbox Code Playgroud)
备注:我没有包含jquery-1.4.4.js在我的视图中,因为它已在布局中引用.
| 归档时间: |
|
| 查看次数: |
9536 次 |
| 最近记录: |