It is necessary to have a unique email id in your database for every registered user, so while registering a user you may need to know if the email id entered by the user is already registered and saved into the database or not, without refreshing the whole page, so this can be done using special Data annotation  attribute in MVC which is called "Remote".Using Remote attribute of data annotation, we can validate if the email id already exists in database or not.

Let's consider we have a Student's table and database, where we will be saving email id of student and each student must have a unique email id, here is the image of the current database table

data-annotation-remote-validation-in-mvc-min.png

Create a new project in your Visual Studio, by navigating to File-> New -> Project -> Select "ASP.NET Web Application Template", provide the Project a name ("RemoteValidationsInMVC") of your choice and click OK.

remote-validations-in-mvc-min.png

Now, let's create a Model class with Data annotation attributes to validate the email, right-click on "Models" folder of your project and then select "Add" and then select "Class"

remote-validations-c-sharp-mvc-min.png

And add a Class, "RegisterModel.cs" with C# code as below

using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace RemoteValidationsInMVC.Models
{
    public class RegisterModel
    {

        [Required]
        [Display(Name = ("Name"))]
        public string Name { get; set; }

        [Required]
        [Display(Name = ("Class"))]
        public string Class { get; set; }

        [Required]
        [DataType(DataType.EmailAddress)]
        [Display(Name = "Email Id")]
        //Using Remote validation attribute   
        [Remote("IsAlreadySignedUpStudent", "Register", ErrorMessage = "EmailId already exists in database.")]
        public string EmailId { get; set; }
       
    }
}

Now as you can see we have used "Remote" attribute here, let me explain it in detail, in the above code

  1. IsAlreadySignedUpStudent = The method which will be called to check if email id exists or not
  2. Register = Is the name of the controller.
  3. ErrorMessage = The error message you want to display to the user when email id is already registered in the database.

Before we add Controller in our project to save and get data from the database, let's connect it to Database using ADO.NET (.edmx), if you are totally new to EDMX you can read more about connecting to the database, fetching/inserting data using Entity framework, I will quickly connect this project to the database.

Right-Click on your Models folder and Click "Add", then select "New Item" -> Select "Data" in Left pane and "ADO.NET" Entity in right-pane.

ado-net-connecting-to-database-for-remote-validations-min.png

Select "EF Designer From database" in next step, then click "Next" -> Select "New Connection" -> Enter your database details, "SQL Server Instance" & "Database", then click "Test Connection" to make sure all settings are correct, if everything is correct Click "OK".

Select "Yes, include the sensitive data in the connection string", click "Next", select the tables which you want to include in your project from the database.

Click "Finish" and your .edmx file is created, and your project is now connected with the database.

Once we are connected to the database, we need to add a Controller in our project, so let's add a Controller, by right-clicking on "Controllers" folder in your project and then Select "Add"->"Controller"

Select MVC Empty controller, give a name (RegisterController.cs) and click OK

Now, we can use the below code to Create method to sign up student details and another to save it, and check If email exists or not using our method "IsAlreadySignedUpStudent"

using RemoteValidationsInMVC.Models;
using System.Linq;
using System.Web.Mvc;

namespace RemoteValidationsInMVC.Controllers
{
    public class RegisterController : Controller
    {
        // GET: Register
        public ActionResult SignUp()
        {
            return View();
        }

        [HttpPost]
        public ActionResult SignUp(RegisterModel ObjModel)
        {
            if (ModelState.IsValid)
            {
                //Model is valid save it in database

                return View();
            }
            else
            {
                //Model is not valid show error
                return View(ObjModel);
            }

        }
        
         public JsonResult IsAlreadySignedUpStudent(string EmailId)
        {
            Student_details student_Details = new Student_details();

            using (var context = new StudentsEntities())
            {
                student_Details = context.Student_details.Where(a => a.EmailId.ToLower() == EmailId.ToLower()).FirstOrDefault();
            }
             

            bool status;
            if (student_Details != null)
            {
                //Already registered  
                status = false;
            }
            else
            {
                //Available to use  
                status = true;
            }

            return Json(status,JsonRequestBehavior.AllowGet);

        }
      
    }

}

Once you have added a controller with the above C# code, we need to add unobtrusive Javascript files in your project, these files help us call C# controller method without reloading the page, so navigate to "Tools"-> "Nuget Package manager"-> Select "Manage NuGet package for solution..." -> then search for "javascript unobtrusive" in the browse tabs

Select "Microsoft.jQuery.Unobtrusive.Validation" and select your project, then Click "Install"

remote-validations-js-unobstrutive-min.png

Once you are done, let's add a View for Sign Up ActionMethod, Go to your controller, and inside SignUp ActionMethod, right-click, Select "Add View"

And use the below razor code 

@model RemoteValidationsInMVC.Models.RegisterModel

@{
    ViewBag.Title = "SignUp";
}
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">

        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

         <div class="form-group">
            @Html.LabelFor(model => model.EmailId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.EmailId, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.EmailId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Class, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Class, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Class, "", new { @class = "text-danger" })
            </div>
        </div>

     

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Sign Up" class="btn btn-primary" />
            </div>
        </div>
    </div>
}

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

As you can see  I have included the JS files like "jquery.validate.min.js" and "jquery.validate.unobtrusive.min.js", which is important for us to validate email id exists or not in the database, without reloading the page.

That's it, we are done with the coding part, build and run your code in the browser.

Now, without posting the form, it's showing instantly that the given email id already exists in the database, This approach will save a lot of time for the user in unnecessary validation.

Here is the demo gif image, when executed the above code in the browser

example-remote-validations-in-mvc-min.gif

If you have any questions, feel free to post your comments in the below comments section.

You may also like to read:

Verify email address exists or not? (With email id validation in C#)