实现此目的的一种方法是从验证操作中添加自定义 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);
}
};
});