在MVC中检查电子邮件的远程验证

时间:2018-12-25 15:10:20

标签: c# ajax attributes remote-validation

我正在使用远程验证来检查数据库中是否已经存在电子邮件,但它不起作用,这是代码:

模型属性

[Remote("IsAlreadyUserExist", "User", HttpMethod = "POST", ErrorMessage = "Email Already Exists.")]
public string Email { get; set; }

控制器

[HttpPost]
public JsonResult IsAlreadyUserExist(string Email)
{

    return Json(IsUserExist(Email));

}

public bool IsUserExist(string Email)
{      
    List<UserProfile> userlist = userRepo.GetUserList();
    var UserEmailId = (from u in userlist
                      where u.Email.ToUpper() == Email.ToUpper()
                      select new { Email }).FirstOrDefault();

    bool status;
    if (UserEmailId != null)
    {
        //Already registered  
        status = false;
    }
    else
    {
        //Available to use  
        status = true;
    }
    return status;
}

我已在底部的“创建”视图中添加了此js。

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

我还尝试将调试器置于IsAlreadyUserExist函数中,但没有成功。

任何想法可能是什么问题?

1 个答案:

答案 0 :(得分:0)

要使RemoteAttibute有效,请在RemoteAttibute属性上编写Email,如下所示:

[Required]
[StringLength(30)]
[Index("Ix_Email",Order =1,IsUnique =true)]
[Remote("IsUserAlreadyExists", "User", AdditionalFields = "Id", ErrorMessage = "User already exists with the provided email")]
public string Email { get; set; }

您正从内存中的数据库中拉出所有用户,只是为了检查某个电子邮件是否已经存在一个用户,考虑到性能,这是非常非常糟糕的。因此,请在IsUserAlreadyExists中编写UserController方法,如下所示:

public JsonResult IsUserAlreadyExists(string Email, int? Id)
{
     var isUserAlreadyExists = db.Users.Any(x => x.Email== Email && x.Id != Id);
     return Json(!isUserAlreadyExists, JsonRequestBehavior.AllowGet);
}

现在,如果要将数据库访问代码移至UserRepository,请按以下步骤进行操作:

public class UserRepository
{
   YourDbContext dbContext = new YourDbContext();

   public bool IsUserAlreadyExistsByEmail(string email, int? id)
   {
      return dbContext.Users.Any(x => x.Email== Email && x.Id != Id);
   }
}

然后按如下所示调用IsUserAlreadyExistsByEmail的{​​{1}}方法:

UserRepository

注意:我没有看到您的存储库代码,因此在这里显示了它应该是如何的通用视图。根据自己的结构使用一切。