我正在使用远程验证来检查我的 asp.net mvc 3 应用程序 (C#) 注册期间用户名的可用性。
我使用 MVC 远程属性验证:
[Remote("IsUserNameAvailable", "User")]
public string UserName { get; set; }
当我返回这个时:
return Json(true, JsonRequestBehavior.AllowGet);
然后我想执行一些操作,例如设置隐藏字段值,该值从操作返回或显示绿色图标图像。我还想返回 true 的 ID。
如何实现这个东西呢?
简而言之,我想做一些关于成功的事情。
实现此目的的一种方法是从验证操作中添加自定义 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);
}
};
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)