Reputation: 316
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();
}
Upvotes: 1
Views: 4615
Reputation: 1018
This will query and return the first entry in the db matching the criteria OR null
db.Users.FirstOrDefault(x => x.UserName == reg.UserName)
So I would just check if that query returns a value or null and set a bool (see code below)
note the x
, you can use another letter or word. maybe data => data.UserName....
or row => row.UserName...
or result => result.UserName...
, it just represents the Model for the db
something like this (rearranged the code a bit as well)
[HttpPost]
public ActionResult Register(UserVIewModel reg) {
if (!ModelState.IsValid)
{
return View(model);
}
// here is the main answer to your question
bool userExists = db.Users.FirstOrDefault(x => x.UserName == reg.UserName) != null;
// and then use the bool to see if you need to return an error
if (userExists) {
// I'm not 100% sure about this part so double-check this
// but I think it's pretty close to this
ModelState.AddModelError("UserName","UserName taken");
return View(model);
}
// If the userExists = false then code continues here
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");
}
Upvotes: 1
Reputation: 6322
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();
}
Upvotes: 5