Nyprez Nyprez - 2 months ago 12
C# Question

MVC - How to check if Username is not already taken?

I'm using database-first and I validating my inputs via ViewModel. However, I would like to check if either

UserName
is already taken in db. How do I do that? This is how far I managed to get (I can validate and save):

[Required]
[StringLength(50)]
[MinLength(3, ErrorMessage = "You must at least have 3 letters")]
public string UserName { get; set; }


And the following is my Register code in controller:

[HttpGet]
public ActionResult Register() {
return View();
}

[HttpPost]
public ActionResult Register(UserVIewModel reg) {
if (ModelState.IsValid)
{
var m = new User {
UserName = reg.UserName,
Email = reg.Email,
FirstName = reg.FirstName,
LastName = reg.LastName,
Password = reg.Password
};

db.Users.Add(m);
db.SaveChanges();

return RedirectToAction("Login");

}
return View();
}

Answer

This is how you can do check on user inside Register() method

[HttpPost]
public ActionResult Register(UserVIewModel reg) {
    if (ModelState.IsValid)
    {

        if (db.Users.Where(u => u.UserName == reg.UserName).Any())
        {
           //Do what do u need to do...
        }
        else
        {
          var m = new User {
            UserName = reg.UserName,
            Email = reg.Email,
            FirstName = reg.FirstName,
            LastName = reg.LastName,
            Password = reg.Password
          };

          db.Users.Add(m);
          db.SaveChanges();

          return RedirectToAction("Login");
        }
    }
    return View();
}