In this tutorial I will show you how to check email ID already exists in database using asp.net MVC.
Razor view: Register.cshtml
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(Account account, string returnUrl)
{
var isEmailIdExists = db.Accounts.Any(x => x.Email == account.Email);
if (isEmailIdExists)
{
ModelState.AddModelError("Email", "User with this email already exists.");
return View(account);
}
account.CreatedOn = DateTime.Now;
account.ModifiedOn = DateTime.Now;
account.IsDeleted = 0;
account.Password = HtmlUtility.Encrypt(account.Password);
if (ModelState.IsValid)
{
db.Accounts.Add(account);
db.SaveChanges();
}
return View(); }
Controller:
@using (@Html.BeginForm("register", "user", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { Class = "signin-form" }))
{
@Html.AntiForgeryToken()
<div class="form-group mb-3">
<label class="label">User Name</label>
@Html.TextBoxFor(model => model.UserName, new { type = "text", required = "required", placeholder = "Enter Username", Class = "form-control" })
@Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })
</div>
<div class="form-group mb-3">
<label class="label">E-MAIL</label>
@Html.TextBoxFor(model => model.Email, new { type = "text", required = "required", placeholder = "Enter Email Address", Class = "form-control" })
@Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
</div>
<div class="form-group mb-3">
<label class="label">ENTER YOUR PASSWORD</label>
@Html.TextBoxFor(model => model.Password, new { type = "password", minlength = "4", required = "required", placeholder = "Password", Class = "form-control" })
@Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
</div>
<div class="form-group">
<button class="form-control btn btn-primary submit px-3" style="text-transform:uppercase;"><i class="fa fa-sign-in"></i> Register</button> </div> }