使用方法:
1。Model中增加Remote Attribute,并指定相应的验证Action路径
public class UsingRemote { [Required] [Remote("IsNumberEven", "GuestBook", ErrorMessage = "数字必须是偶数!")] public int EvenNumber { get; set; } }
IsnumberEven为Action,GuestBook为Controller
2。Controller中创建相应验证方法:
[HttpGet] public JsonResult IsNumberEven(int EvenNumber) { return Json(EvenNumber % 2 == 0, JsonRequestBehavior.AllowGet); }
注意:必须为[HttpGet],返回结果必须为Json
3.View中添加元素:
@using Mvc4Application.Models@model UsingRemote@{ ViewBag.Title = "RemoteAttribute";}@{Html.EnableClientValidation(); Html.EnableUnobtrusiveJavaScript();}RemoteAttribute
@using (Html.BeginForm("RemoteAttribute", "GuestBook")){ @Html.EditorForModel() }
注意:因为Remote实际为通过调用JQuery实现的异步远程调用,所以必须在_layout.cshtml中同时引用了如下三个文件:
且在该view中声明了:
@{Html.EnableClientValidation(); Html.EnableUnobtrusiveJavaScript();}
或在web.config中声明: