为什么我的远程属性不能用于注册方法和视图?

时间:2016-06-30 16:34:20

标签: c# asp.net asp.net-mvc

当我从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*"));

1 个答案:

答案 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);
}