Eng.Sameh Shreif
Eng.Sameh Shreif

Reputation: 11

Check if the user already exists in ASP.NET MVC

This is the controller:

public class UserController : Controller
{
    ResturantEntities db = new ResturantEntities();

    public ActionResult Index()
    {
        var data = db.User.OrderByDescending(z => z.ID).Select(s => s).ToList();
        return View(data);
    }

    public ActionResult Register()
    {

        return View();
    }
    [HttpPost]
    public ActionResult Register(UserVM obj)
    {
        if (ModelState.IsValid)
        {

            User newobj = new User();
            newobj.UserName = obj.UserName;
            newobj.Email = obj.Email;
            newobj.Password = obj.Password;
            newobj.Address = obj.Address;
            db.User.Add(newobj);
            db.SaveChanges();
            return RedirectToAction("Index");

        }
        else
        {
            return RedirectToAction("Register");
        }
    }
}

I want to add an if condition before newobj.Email = obj.Email; to check if the email exists in db or not; if not exists so it will be added.

Upvotes: 0

Views: 13945

Answers (1)

TanvirArjel
TanvirArjel

Reputation: 32069

First welcome to Stack Overflow.

Now write your Register POST method as follows:

[HttpPost]
public ActionResult Register(UserVM obj)
{
    if (ModelState.IsValid)
    {
        var isEmailAlreadyExists = db.User.Any(x => x.Email == obj.Email);
        if(isEmailAlreadyExists)
        {
            ModelState.AddModelError("Email", "User with this email already exists");
            return View(obj)
        }

        User newobj = new User();
        newobj.UserName = obj.UserName;
        newobj.Email = obj.Email;
        newobj.Password = obj.Password;
        newobj.Address = obj.Address;
        db.User.Add(newobj);
        db.SaveChanges();
        return RedirectToAction("Index");

    }

    return View(obj)
}

Upvotes: 5

Related Questions