一、web.config加入
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
二、Controllers验证方法
using System;
using System.Globalization;
using System.Web.Mvc;
using System.Web.UI;
using Mvc3RemoteVal.Models;
namespace Mvc3RemoteVal.Controllers {
public class ValidationController : Controller {
/// <summary>
/// 检验商家昵称是否已存在
/// </summary>
/// <param name="sellerNick">昵称,定义的变量名需要与Model中的属性名保持一致,大小写忽略不计</param>
/// <returns>bool</returns>
[OutputCache(Location = OutputCacheLocation.None, NoStore = true)] //清除缓存
public JsonResult CheckSellerNick(string sellerNick)
{
bool isValidate = false;//true代表不存在,false代表存在
if (!SellerAccess.CheckSellerNick(sellerNick))
{
isValidate = true;
}
return Json(isValidate, JsonRequestBehavior.AllowGet);
}
}
}
三、model
public class UserModel {
[Required]
[StringLength(6, MinimumLength = 3)]
[Remote("CheckSellerNick", "Validation",ErrorMessage="该昵称已存在")]//ActionName,Controller,错误信息
public override string SellerNick{ get; set; }
}
四、View引用
<script src="@Url.Content("~/Scripts/jquery-1.7.1.js")"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>