How can i can create a validation where i can only create 1 user with that name
my code
is this
[HttpPost]
public ActionResult Create(Klant klant)
{
ModelState.AddModelError("Firma", "Firma already exists");
if (ModelState.IsValid)
{
db.Klanten.Add(klant);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(klant);
}
now can i create 0 users because i get always the error firma already exists with my addmodelerror
First, check if your modelstate is valid. If it isn't, let the user know the had some invalid fields.
If it is valid, check if that username already exists, and if it does, return the model with your added model error:
public ActionResult Create(Klant klant)
{
if (ModelState.IsValid)
{
if(db.Klanten.Any(k => k.Username == klant.Username)
ModelState.AddModelError("Firma", "Firma already exists");
else
{
db.Klanten.Add(klant);
db.SaveChanges();
return RedirectToAction("Index");
}
}
return View(klant);
}
This approach is more user-friendly, as the last error they can have is a username already taken, and they'll only have to change that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With