mvc duplicate user validation error

6k views Asked by At

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

3

There are 3 answers

0
Daemon025 On

Put

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

after "if" and before return statement

0
Jonesopolis On

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.

0
Mousa Al-Kalouti On

I know this answer is late but I love to share this for new viewers. And I know this approach is the same as the other answers but I think it's more clean and easier for maintenance:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Klant klant)
{
    if (!ModelState.IsValid)
        return View(klant);

    if (db.Klanten.Any(k => k.Username == klant.Username)
    {
        ModelState.AddModelError("Firma", "Firma already exists");
        return View(klant);
    }

    db.Klanten.Add(klant);
    db.SaveChanges();
    return RedirectToAction("Index");
}

And don't forget to add [ValidateAntiForgeryToken] above the Action Method and @Html.AntiForgeryToken(); in the razor view inside your form. for protection from hackers attacks. It is an action filter where the requests made to actions that have this filter applied are blocked unless the request includes a valid antiforgery token.

You can read more about antiforgery token inside this article https://www.c-sharpcorner.com/blogs/validateantiforgerytoken-attribute-in-asp-net-mvc