0

I am using remote validation for checking if email already exist in database but it is not working, here is the code:

Model Property

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

Controller

[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;
}

I have added this js in my Create view at the bottom.

<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>

I also tried putting debugger in IsAlreadyUserExist function but it is not hitting there.

Any idea what could be the problem?

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
Learner1
  • 99
  • 1
  • 11

1 Answers1

0

For making RemoteAttibute working, write your RemoteAttibute on Email property as follows:

[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; }

You are pulling all the users from the database in memory just for checking whether a user already exists with a certain email, which is very very bad considering the performance standpoint. So write IsUserAlreadyExists method in the UserController as follows:

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

Now if you want to move the database access code to your UserRepository then do it as follows:

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

Then call the IsUserAlreadyExistsByEmail method of the UserRepository as follows:

public JsonResult IsUserAlreadyExists(string Email, int? Id)
{
     var isUserAlreadyExists = userRepo.IsUserAlreadyExistsByEmail(Email,Id);
     return Json(!isUserAlreadyExists, JsonRequestBehavior.AllowGet);
}

Note: I didn't see your repository code so I have shown here a generalized view of how it should be. Use everything according to your own structure.

TanvirArjel
  • 30,049
  • 14
  • 78
  • 114