Mvc user duplicate error

How can I create validation where I can only create 1 user with this name

my code

- this is

  [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 i can create 0 users because i always get an error that already exists with my addmodelerror

+3


source to share


2 answers


First check if your model state is correct. If not, let the user know they have some invalid fields.

If so, check if that username exists, and if so, return the model with the 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 might have is the username already and they only have to change that.

+4


source


Put

ModelState.AddModelError("Firma", "Firma already exists");  

      



after the "if" and before the return statement

0


source







All Articles