一種方法是從驗證動作添加自定義HTTP響應頭:
public ActionResult IsUserNameAvailable(string username)
{
if (IsValid(username))
{
// add the id that you want to communicate to the client
// in case of validation success as a custom HTTP header
Response.AddHeader("X-ID", "123");
return Json(true, JsonRequestBehavior.AllowGet);
}
return Json("The username is invalid", JsonRequestBehavior.AllowGet);
}
現在在客戶端上,我們顯然對用戶名的標準格式和輸入字段:
@model MyViewModel
@using (Html.BeginForm())
{
@Html.EditorFor(x => x.UserName)
@Html.ValidationMessageFor(x => x.UserName)
<button type="submit">OK</button>
}
現在拼圖的最後一塊是一個complete
處理程序附加到用戶名字段的remote
規則:
$(function() {
$('#UserName').rules().remote.complete = function (xhr) {
if (xhr.status == 200 && xhr.responseText === 'true') {
// validation succeeded => we fetch the id that
// was sent from the server
var id = xhr.getResponseHeader('X-ID');
// and of course we do something useful with this id
alert(id);
}
};
});
哇....真棒.......非常感謝...... –