远程属性不再起作用

时间:2016-02-12 07:12:25

标签: jquery json asp.net-mvc repository

我有Project,我使用了Repository和Interface。我想通过Remote属性控制Duplicate UserName。我在_UserRepository中使用了检查重复UserName的方法。

我的用户模型

public partial class Users
{
    public Users()
    { this.NEWSs = new HashSet<NEWS>(); }
    public string Name { get; set; }
    public string Family { get; set; }
    public string Email { get; set; }
    [Required]
    [Remote("UserNameExists", "Users", "Username is already taken.")]
    public string UserName { get; set; }
    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    public string PassWord { get; set; }

_UserRepository

public   Models.Users GetUserByName(string  User)
{
    var src = from b in DbContext.Userss where b.UserName == User select b.UserName;
    return DbContext.Userss.Find(src);
}

UserNameExists UsersController中的代码

public virtual JsonResult UserNameExists(string UserName)
{
    Users user = userRepository.GetUserByName(UserName);
    return user == null ?
        Json(true, JsonRequestBehavior.AllowGet) :
        Json(string.Format("{0} is not available.", UserName),
            JsonRequestBehavior.AllowGet);
}

运行项目时运行Inspector并打开控制台。我看到下面的错误。

http://localhost:57553/Users/UserNameExists?area=Username%20is%20already%20taken.&UserName=mz1368 500(内部服务器错误)

但是,我认为代码是正确的以及JSON或jQuery Reference的问题。

1 个答案:

答案 0 :(得分:0)

将您的属性更改为:

[Remote("UserNameExists", "Users", HttpMethod = "POST", ErrorMessage = "Username is already taken.")]

同样@Stephen提到你可以简化你的行动方法,像这样:

[HttpPost]
public ActionResult UserNameExists(string UserName)
{
    if (userRepository.IsUserExist(UserName)) return Json(false);
    return Json(true);
}

public bool IsUserExist(string user)
{
    return DbContext.Users.Any(x => x.User == user);
}