MVC中使用RemoteAttribute异步远程验证

使用方法:

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();}

<h2>RemoteAttribute</h2>
@using (Html.BeginForm("RemoteAttribute", "GuestBook"))
{
    @Html.EditorForModel()                             
    <button type="submit">submit</button>                          
}

注意:因为Remote实际为通过调用JQuery实现的异步远程调用,所以必须在_layout.cshtml中同时引用了如下三个文件:

   <script src="@Url.Content("~/Scripts/jquery-1.7.1.min.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>

且在该view中声明了:

@{Html.EnableClientValidation(); Html.EnableUnobtrusiveJavaScript();}

或在web.config中声明:

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

 

转载于:https://www.cnblogs.com/Finding2013/archive/2013/05/09/3068585.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值