当我从UserName
文本框移动焦点时,页面不会呈现错误消息,也不允许页面提交。
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.UserName};
user.UserName = model.UserName;
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await this.UserManager.AddToRoleAsync(user.Id, model.Name);
return RedirectToAction("Index","User");
}
AddErrors(result);
}
return View(model);
}
[HttpPost]
public JsonResult doesUserNameExist(string UserName)
{
var user = Membership.GetUser(UserName);
return Json(user == null);
}
在我的AccountViewModel中:
public class RegisterViewModel
{
[Required]
[Display(Name = "User Name")]
[Remote("doesUserNameExist", "Account", ErrorMessage = "{0} User name already exists. Please enter a different user name.")]
public string UserName { get; set; }
}
在我的捆绑配置中:
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
答案 0 :(得分:1)
您应该在[HttpPost]
之前移除doesUserNameExist
并像这样编辑doesUserNameExist
:
public JsonResult doesUserNameExist(string username)
{
var user = Membership.GetUserByName(username.Trim());
return user == null ?
Json(true, JsonRequestBehavior.AllowGet) :
Json(string.Format("{0} is not available.", username),
JsonRequestBehavior.AllowGet);
}