參照地址:http://msdn.microsoft.com/en-us/library/gg508808%28VS.98%29.aspx#Y2142
一、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 {
[OutputCache(Location = OutputCacheLocation.None, NoStore = true)] //清除緩存
public class ValidationController : Controller {
/// <summary>
/// 檢驗商家暱稱是否已存在
/// </summary>
/// <param name="sellerNick">暱稱</param>
/// <returns>bool</returns>
public JsonResult CheckSellerNick(string sellerNick)
{
bool isValidate = false;
if (!SellerAccess.CheckSellerNick(sellerNick))
{
isValidate = true;
}
return Json(isValidate, JsonRequestBehavior.AllowGet);
}
}
}
三、model
public class CreateUserModel : EditUserModel {
[Required]
[StringLength(6, MinimumLength = 3)]
[Remote("CheckSellerNick", "Seller",ErrorMessage="該暱稱已存在")]//ActionName,Controller,錯誤信息
[RegularExpression(@"(/S)+", ErrorMessage = "White space is not allowed.")]
[Editable(true)]
public override string UserName { get; set; }
}
四、View引用
<script src="../../Content/jquery/jquery-1.4.4.js" type="text/javascript"></script>
<script src="../../Content/jquery/jquery.validate.min.js" type="text/javascript"></script>
<script src="../../Content/jquery/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>