Check UserName Exists or Not instantly In ASP.NET MVC

Many times, we need to check instantly whether a record already exists in the database or not. For example, at the time of signup, we need to check if the user is already registered with current Email id, or the username is already taken. So, to achieve these functionalities, there are many methods, but in ASP.NET MVC, there is a very easy way to achieve these types of functionalities, i.e. with the help of remote attributes. Let's learn step by step how to check user instantly, using remote attribute in ASP.NET MVC.

What is Remote Validation in ASP.NET MVC ?

Remote is the attribute for validation in Data Annotation, which is used in model class to validate records instantly. Let's demonstrate the aforementioned concept by creating sample ASP.NET MVC application.
Step 1 - Create an MVC Application

Now, let us start with a step-by-step approach from the creation of a simple MVC application.
  1. Go to "Start", followed by "All Programs" and select "Microsoft Visual Studio 2015".
  2. Click "File", followed by "New" and click "Project". 
  3. Select "ASP.NET Web Application Template", provide the Project a name of your choice and click OK. 
After clicking, the following window will appear.

    Step 2 - Create Model Class

    Now, let us create the model class, named RegisterModel.cs, by right clicking on Models folder, as
    shown in the screenshot.


    After creating the class, write the following properties in RegisterModel.cs class.

    RegisterModel.cs

    using System.ComponentModel.DataAnnotations;  
    using System.Web.Mvc;  
      
    namespace RemoteValiDationInMVC.Models  
    {  
        public class RegisterModel  
        {  
              
            [Required]  
            [DataType(DataType.EmailAddress)]  
            [Display(Name ="Enter EmailId")]  
            //Using Remote validation attribute   
            [Remote("IsAlreadySigned", "Register",HttpMethod ="POST", ErrorMessage = "EmailId already exists in database.")]  
            public string UserEmailId { get; set; }  
            [Required]  
            public string Designation { get; set; }  
                     
            [Required]  
            [DataType(DataType.Password)]  
            [Display(Name =("Choose Password"))]  
            public string PassWord { get; set; }  
      
        }  
    }  

    In the preceding code, we have used Remote attribute for UserEmaiId model class method with some properties which are explained below.



    In the above image, we have defined a few properties of Remote attribute to work on remote validation properly, let's know them in brief.
    • IsAlreadySigned
      This is the JsonResult method which checks the details from database and returns true or false.
    • Register
      This is MVC Controller name and inside that, IsAlreadySigned JsonResult method is defined to check the details from database.
    • HttpMethod
      This is HttpMethod type which is called on Remote attribute e.g. Get , Put , Post. This is optional to define.
    • ErrorMessage
      This is used to show the message at client side. 
    There are many optional properties of Remote attribute which are used as per the validation requirements.
    Step 3 - Add Controller Class
    Now, let us add the MVC 5 Controller, as in the following screenshot.


    After clicking on Add button, it will show the window. Specify the Controller name as Register with suffix Controller. Now, modify the default code in RegisterController.cs class file and create JsonResult method. After modifying, the code will look like as follows.

    RegisterController.cs

    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web.Mvc;  
    using RemoteValiDationInMVC.Models;  
      
    namespace RemoteValiDationInMVC.Controllers  
    {  
        public class RegisterController : Controller  
        {  
            // GET: Register  
            [HttpGet]  
            public ActionResult SignUp()  
            {  
                return View();  
            }  
            [HttpPost]  
            public ActionResult SignUp(RegisterModel ObjModel )  
            {  
                if (ModelState.IsValid)  
                {  
      
                    return View();  
      
                }  
                else  
                {  
      
                    return View();  
      
                }  
      
            }  
            [HttpPost]  
            public JsonResult IsAlreadySigned(string UserEmailId)  
            {  
                  
                return Json(IsUserAvailable(UserEmailId));  
      
            }  
            public bool IsUserAvailable(string EmailId)  
            {  
                // Assume these details coming from database  
            List<RegisterModel> RegisterUsers = new List<RegisterModel>()  
            {  
      
                new RegisterModel {UserEmailId="vithal.wadje@abc.com" ,PassWord="compilemode",Designation="SE"},  
                new RegisterModel {UserEmailId="Sudhir@abc.com" ,PassWord="abc123",Designation="Software Dev"}  
      
            };  
                var RegEmailId = (from u in RegisterUsers  
                                  where u.UserEmailId.ToUpper() == EmailId.ToUpper()  
                                  select new { EmailId }).FirstOrDefault();  
      
                bool status;  
                if (RegEmailId!=null)  
                {  
                    //Already registered  
                    status = false;  
                }  
                else  
                {  
                    //Available to use  
                   status = true;  
                }  
                    
                return status;  
          }            
        }  
      
    }  

    Note

    In the preceding code, IsAlreadySigned returns the JSON data at client side and it takes the UserEmailId as input parameter, the name of which, must match with the get set property defined under the remote attribute.

    Step 4 - Create View

    Now, let's create StronglyTyped View named SignUp from RegisterModel class.


    Click on Add button. It will create the View named SignUp. Now, open the SignUp.cshtml View. You will see some default code which is generated by MVC scaffolding template. Let's now, modify the default code to make as per our requirement.

    SignUp.cshtml

    @model RemoteValiDationInMVC.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.UserEmailId, htmlAttributes: new { @class = "control-label col-md-2" })  
                <div class="col-md-10">  
                    @Html.EditorFor(model => model.UserEmailId, new { htmlAttributes = new { @class = "form-control" } })  
                    @Html.ValidationMessageFor(model => model.UserEmailId, "", new { @class = "text-danger" })  
                </div>  
            </div>  
      
            <div class="form-group">  
                @Html.LabelFor(model => model.Designation, htmlAttributes: new { @class = "control-label col-md-2" })  
                <div class="col-md-10">  
                    @Html.EditorFor(model => model.Designation, new { htmlAttributes = new { @class = "form-control" } })  
                    @Html.ValidationMessageFor(model => model.Designation, "", new { @class = "text-danger" })  
                </div>  
            </div>  
      
            <div class="form-group">  
                @Html.LabelFor(model => model.PassWord, htmlAttributes: new { @class = "control-label col-md-2" })  
                <div class="col-md-10">  
                    @Html.EditorFor(model => model.PassWord, new { htmlAttributes = new { @class = "form-control" } })  
                    @Html.ValidationMessageFor(model => model.PassWord, "", new { @class = "text-danger" })  
                </div>  
            </div>  
      
            <div class="form-group">  
                <div class="col-md-offset-2 col-md-10">  
                    <input type="submit" value="SignUp" 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>  

    After adding the Model, add View and Controller into our project, the Solution Explorer will look like the following.


    Step - 5 

    Now, run the application and type emaild id which is already in the  list that we defined in the RegisterController class.

    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.
    Note
    • Since this is a demo, it might not be using proper standards. So, improve it as per your own skills.
    Summary
    I hope this article is useful for all readers. If you have any suggestions, please contact me.
    Don't Forget To 

    Post a Comment

    www.CodeNirvana.in

    Protected by Copyscape
    Copyright © Compilemode