Routing in ASP.NET MVC

In today's modern web application each and every thing is important including request URL pattern of the application to make application more traffic driven and user friendly. In earlier ASP.NET application all the user request are mapped with physical file location that is with .aspx pages. These types of URL pattern are won't be customized to make it user, SEO friendly and most of the time in ASP.NET application to overcome these URL drawback URL rewriting technique is used, But still it unable to fulfill the expected requirement.
In ASP.NET MVC, URL pattern is completely different as compare to the ASP.NET application URL pattern, So lets learn about the ASP.NET MVC routing.

What is routing in ASP.NET MVC ?
Routing is the concept in ASP.NET MVC which is used to define the URL pattern for the ASP.NET MVC application incoming user request.
There are two types of routing supported by ASP.NET MVC
  • Conventional based routing 
  • Attribute routing
Conventional Routing
The default routing in ASP.NET MVC is a conventional routing which is get added in RouteConfig.cs file when we create ASP.NET MVC application, These type of routing defined in RouteConfig.cs file .

The following is the default routing

Suppose we have Employee method in ASP.NET MVC application and we want to define the URL pattern that how this method can be called by end user then routing pattern can be defined as in the following

Attribute Routing
The routing which is defined on controller or action level is called as attribute routing . These type of routing is only supports in  MVC 5 version onward
I hope from preceding brief explanation you have learned about the ASP.NET MVC routing, In my next article we will learn each of the routing in details with real time examples.
    The preceding is the example of attribute routing which can be enabled in RouteConfig.cs by calling MapMvcAttributeRoutes method of RouteCollection class
    
    Key Points
    • RouteCollection class is used for routing which uses the System.Web.Routing namespace
    • ASP.NET MVC 5 supports two types of routing that is conventional and attribute routing
    • Conventional based is the default routing in ASP.NET MVC 
    • Attribute routing can be defined on controller as well as action level
    • All routes should be registered into the Global.asax file .
    • Every ASP.NET MVC application must have at least one routing defined
    • We can define multiple routing in single application in this case it executed sequence wise as it defined.
    • If we are defining two route templates then the route name must be different across the application level
    Summary
    I hope, this article is useful for all the readers. If you have any suggestions, please contact me. In my next article we will learn real time example of conventional and attribute routing.

    Don't Forget To  

    Upload Images on Server Folder Using ASP.NET MVC

    Sometimes we require to upload the images on the server folder for a specific requirement, so by considering this requirement I have decided to write this article. Let's start it step by step.

    Step 1: Create an ASP.NET MVC Application.

    Now let us start with a step by step approach to the creation of a simple  ASP.NET MVC application as in the following:
    1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
    2. Click "File", then "New" and click "Project", then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click OK. After clicking, the following window will appear:

     Step 2: Create Model Class

    Now let us create the model class named FileUploadModel.cs by right clicking on the Models folder as in the following screenshot:


    Write the following code into the FileUploadModel.cs as follows

    FileUploadModel.cs 
    public class FileUploadModel   
          {    
              [DataType(DataType.Upload)]    
              [Display(Name = "Upload File")]    
              [Required(ErrorMessage = "Please choose file to upload.")]    
              public string file { get; set; }    
            
          }   
    
    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 FileUpload with suffix Controller.

    Note:

    The controller name must have a suffix as 'Controller' after specifying the name of the controller. Now let's modify the default code in FileUploadController.cs to read uploaded files. There are many ways to read the uploaded files in the controller, but in this article we will learn two ways to read the uploaded files into the controller which are listed below,
    • HttpRequestBase: We can use HttpRequestBase class property named Request to get collection of files or single file.
    • HttpPostedFileBase: This is the easiest way to read the uploaded files into the controller .
    Now let's open the FileUploadController.cs class file and write the following code to read the file using HttpRequestBase class.

    FileUploadController.cs
     
               [HttpPost]    
               public ActionResult UploadFiles(HttpPostedFileBase file)    
               {    
                   if (ModelState.IsValid)    
                   {    
                       try    
                       {    
                             
                           //Method 2 Get file details from HttpPostedFileBase class    
            
                           if (file != null)    
                           {    
                               string path = Path.Combine(Server.MapPath("~/UploadedFiles"), Path.GetFileName(file.FileName));    
                               file.SaveAs(path);     
                           }    
                           ViewBag.FileStatus = "File uploaded successfully.";    
                       }    
                       catch (Exception)    
                       {      
                           ViewBag.FileStatus = "Error while file uploading."; ;    
                       }                  
                   }    
                   return View("Index");    
               }  
    

    Following is the whole source code of FileUploadController.cs file which will look like as follows,

        using System;    
        using System.IO;    
        using System.Web;    
        using System.Web.Mvc;    
            
        namespace UploadingFilesUsingMVC.Controllers    
        {    
            public class FileUploadController : Controller    
            {    
                // GET: FileUpload    
                public ActionResult Index()    
                {    
                    return View();    
                }    
                [HttpPost]    
                public ActionResult UploadFiles(HttpPostedFileBase file)    
                {    
                    if (ModelState.IsValid)    
                    {    
                        try    
                        {    
                              
            
                            if (file != null)    
                            {    
                                string path = Path.Combine(Server.MapPath("~/UploadedFiles"), Path.GetFileName(file.FileName));    
                                file.SaveAs(path);    
            
                            }    
                            ViewBag.FileStatus = "File uploaded successfully.";    
                        }    
                        catch (Exception)    
                        {    
            
                            ViewBag.FileStatus = "Error while file uploading.";    
                        }    
                         
                    }    
                    return View("Index");    
                }    
            }    
        }   
    

    Step 4 : Creating view named Index using FileUploadModel class

    Right click on The View folder of created application and choose add view, select FileUploadModel class and choose create scaffolding template,
    Click on Add button, then it will create the view named index. Now open the Index.cshtml view, then the following default code you will see which is generated by MVC scaffolding template as,
     
    Index.cshtml

    @model UploadingFilesUsingMVC.Models.FileUploadModel
    
    @{
        ViewBag.Title = "www.compilemode.com";
    }
    
    @using (Html.BeginForm("UploadFiles", "FileUpload", FormMethod.Post,new { enctype = "multipart/form-data" }))
    {
        @Html.AntiForgeryToken()
        
        <div class="form-horizontal">
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.file, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.file, new { htmlAttributes = new { @class = "form-control", @type="file"} })
                    @Html.ValidationMessageFor(model => model.file, "", new { @class = "text-danger" })
                </div>
            </div>
            
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Upload" class="btn btn-primary" />
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10 text-success">
                    @ViewBag.FileStatus
                </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>
    


    Step 4 : Create a folder named UploadedFiles or as you wish to save uploaded files

    Right click on created ASP.NET MVC application, solution explorer and choose add new item, then Add New Folder. After adding the model, view, controller and UploadedFiles folder to save the file. Solution explorer will look like as follows,


    Now we have done all coding to upload files.

    Step 5: Now run the application. 

    After running the application initial screen will look as follows

    Now click on Upload button without selecting file then the following error message is visible which we have defined in model class as,

     Now browse the file and click on upload button, It will show the following message after successfully uploading the file as,

    Now lets see the UploadedFiles folder where our uploaded files are saved, Browse the folder or move the mouse cursor or image then uploaded image will look like as follows,

    I hope from all the preceding examples we have learned how to upload files on server folder.

    Note:
    • HttpPostedFileBase instance name must be a file.
    • Model class property name must be file so it can generate the input type file .
    • Its important to define enctype = "multipart/form-data" in form action otherwise file value will be null in controller .
    • Since this is a demo, it might not be using proper standards, so improve it depending on your skills.

    Summary

    I hope this article is useful for all readers. If you have any suggestions please contact me.

    Don't Forget To 

    Bind Country List Using CultureInfo In ASP.NET MVC

    In this article we will learn how to populate list of countries using C# globalization class which is capable to display the countries list.

    Now let's start creating a simple MVC  application to demonstrate how to get list of countries without database in ASP.NET MVC using Globalization class

    Step 1: Create an ASP.NET MVC Application.

    Now let us start with a step by step approach from the creation of a simple MVC application as in the following,
    1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
    2. "File", then "New" and click "Project", then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click OK. After clicking, the following window will appear,

    Step 2: 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 Home with suffix Controller.
    Now modify the default code in HomeController.cs class file and create the action methods, after modifying the code will look like as follows,
    HomeController.cs
     
    using System.Collections.Generic;
    using System.Globalization;
    using System.Web.Mvc;
    
    namespace DisplayCountryList.Controllers
    {
        public class HomeController : Controller
        {
            // GET: Home
            public ActionResult Index()
            {
                List<string> CountryList = new List<string>() ;
                CultureInfo[] CInfoList = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
                foreach (CultureInfo CInfo in CInfoList)
                {
                    RegionInfo R = new RegionInfo(CInfo.LCID);
                    if (!(CountryList.Contains(R.EnglishName)))
                    {
                        CountryList.Add(R.EnglishName);
                    }
                }
    
                CountryList.Sort();
                ViewBag.CountryList = CountryList;
                return View();
            }
        }
    }

    Step 3: Create View

    Right click on view folder or near Index Action method and Add view with name Index and modify the existing view code , After modifying the code the Index.cshtml will be look like as follows

    @{
        ViewBag.Title = "www.compilemode.com";
    }
    @using (Html.BeginForm()) 
    {
        @Html.AntiForgeryToken()
        
        <div class="form-horizontal">
            <hr />
            <div class="form-group">
                <label class="col-md-2 control-label">Select Country</label>
                <div class="col-md-10">
                    @Html.DropDownList("CountryList",new SelectList(ViewBag.CountryList),new {@class = "form-control" })
                </div>
            </div>
    
            
        </div>
    }
    
    
    In the preceding code snippet we are binding DropDownList with ViewBag in which country list is assigned into the controller class.
    Step 4: Run application
     Now run the application we will see dropdownlist having list of countries as shown in the following screen shot


    Now Expand dropdownlist to see the other counties as shown in the following screen shot


    I hope from all the preceding examples,  you learned how to display country list without Database in ASP.NET MVC.
    Note:
    • Perform changes in code as per your requirement  its just example .
    • Follow proper standards which might be not meet with this given code.
    • It will not display all county list but its shows list major around 144 countries .
    Summary
    I hope this article is useful for all readers, If you have a suggestion then please contact me.
    Don't Forget To 

    Hosting ASP.NET MVC Application On IIS

    In my previous articles we have learned how to create MVC application and how to publish ASP.NET MVC application, Now in this article we will learn how to host ASP.NET MVC application on IIS . Hosting is required to make any application accessible to the end-user publicly on web. So, in this article, we will learn how to host ASP.NET  MVC application in IIS 10. The following steps are required to host any application.
    If you don't know how to develop and publish ASP.NET MVC application then please refer to following step by step tutorial link to learn about it.
    I hope you have learned required two steps that is developing and publishing ASP.NET MVC application, Now lets start hosting MVC application on IIS.

    Move the published code on Hosting Server
     
    Copy the "Published files" which we have seen in our previous article Publishing ASP.NET MVC Application Using File System and paste those on respective Servers where you want to host the ASP.NET MVC application. In our last article we have published ASP.NET MVC application in the E drive of my Server, as shown in the following image .



    Open IIS Manager
     
    Now, open the IIS Manager from Windows menu or in any other ways you have known.
     

    The above image is of IIS 10 Manager of my Windows 10 machine. The view as well as options might be different on your machine depending on the OS version.
     
    Add Website to host MVC application

    Right click on "Site" in IIS and click on add new website, as shown in the following screenshot.


    After clicking on "Add Website" option, it displays the following configuration window.
     
     
    I hope you understood the preceding configuration by highlighted text.
     
    Define Site Name & Application Pool
     
    Define the site name which will be useful to uniquely identify the site within the IIS server. After specifying the site name, choose the application pool from available pools. You can even create a custom application pool with any desired name. Currently, our IIS manager has the following application Pools.


    Choose the application pool depending on your application configuration. In this article, we are going to choose DefaultAppPool.
    Browse and select Published Folder path
    Now, choose the physical location of published code files by clicking on "Browse" button, as shown in the following image. 
     
     
     
    Now, click on "OK" button.
     
    Define IP address & Port
     
    Choose one IP address from the list of available IP addresses and define the unique port number for the application, which will be unique within the defined IP address.

    Choose Protocol & Host name (optional )
     
    Choose the protocol for your application i.e HTTP or HTTPS which requires port 443 to be open and choose the Host name which will be used publicly to access the application. After defining all the configurations, the web site configuration window will look like this.

    Now, click on OK button. It will create and add the application in IIS.
    Browse the application using web browser
    Browse the hosted application using your system (PC/Laptop) browser , Click on browse hyperlink which is  highlighted in the following image 
     

    After clicking on preceding IIS shown image browse hyperlink, then application will open in your default web browser as shown in the following image
     
     
     
    Preceding is our IIS hosted ASP.NET MVC application which is running in browser.

    Note
    • This article is just guideline to show how to host ASP.NET MVC web API application on IIS .
    • Optimize the speed by setting debug as false etc., from web.config file as per your skills. 
    • In this article, the optimization is not covered in depth.
    • Configure the authentication in IIS as per your requirement .
    Summary
    I hope, this article is useful for all the readers to learn about hosting ASP.NET MVC web application on IIS. If you have any suggestions, please contact me.

    Don't Forget To 

    Downloading Binary Files From SQL DataBase Using ASP.NET MVC

    This articles explains the step by step how to download the files in ASP.NET MVC from database which is stored in a binary format , So lets learn step by step so beginners also can also understand .

    Step 1 : View Binary formatted Uploaded Files

    Step 2: Create an MVC Application.
    Now, let us create a simple MVC application to download the uploaded  file as:
    1. "Start", followed by "All Programs" and select "Microsoft Visual Studio 2015".
    2. Click "File", followed by "New" and click "Project". Select "ASP.NET Web Application Template", provide the Project a name as you wish and click OK. After clicking, the following Window will appear:
    Step 3: Create Model Class
    Now, let us create the model class file, named FileDetailsModel.cs, by right clicking on Models folder and define the following properties  as:
    public class FileDetailsModel  
       {  
           public int Id { get; set; }  
           [Display(Name = "Uploaded File")]  
           public String FileName { get; set; }  
           public byte[] FileContent { get; set; }  
      
      
       }  
    Step 4 : Create Stored Procedure
    Now Create the stored procedure to view the uploaded files using following script as
    CREATE Procedure [dbo].[GetFileDetails]  
    (  
    @Id int=null  
    )  
    as  
    begin  
    select Id,FileName,FileContent from FileDetails  
    where Id=isnull(@Id,Id)  
    End  
     I hope same you have created ;
    Step 5 : Add Controller Class
    Now, let us add ASP.NET MVC controller, as shown in the screenshot, given below:

    After clicking Add button, it will show the Window. Specify the Controller name as Home with suffix Controller. Now, let's modify the default code of Home controller . After modifying the code of Homecontroller class, the code will look like:
    HomeController.cs
    using System;  
        using System.Collections.Generic;  
        using System.IO;  
        using System.Linq;  
        using System.Web;  
        using System.Web.Mvc;  
        using Dapper;  
        using System.Configuration;  
        using System.Data.SqlClient;
        using FileUploadDownLoadInMVC.Models;  
        using System.Data;  
          
        namespace FileUploadDownLoadInMVC.Controllers  
        {  
            public class HomeController : Controller  
            {  
                 
                #region Upload Download file  
                public ActionResult Index()  
                {  
                    return View();  
                }  
                       
                [HttpGet]  
                public FileResult DownLoadFile(int id)  
                {  
          
          
                    List<FileDetailsModel> ObjFiles = GetFileList();  
          
                    var FileById = (from FC in ObjFiles  
                                    where FC.Id.Equals(id)  
                                    select new { FC.FileName, FC.FileContent }).ToList().FirstOrDefault();  
          
                    return File(FileById.FileContent, "application/pdf", FileById.FileName);  
          
                }  
                #endregion  
         
                #region View Uploaded files  
                [HttpGet]  
                public PartialViewResult FileDetails()  
                {  
                    List<FileDetailsModel> DetList = GetFileList();  
          
                    return PartialView("FileDetails", DetList);  
          
          
                }  
                private List<FileDetailsModel> GetFileList()  
                {  
                    List<FileDetailsModel> DetList = new List<FileDetailsModel>();  
          
                    DbConnection();  
                    con.Open();  
                    DetList = SqlMapper.Query<FileDetailsModel>(con, "GetFileDetails", commandType: CommandType.StoredProcedure).ToList();  
                    con.Close();  
                    return DetList;  
                }  
         
                #endregion       
                #region Database connection  
          
                private SqlConnection con;  
                private string constr;  
                private void DbConnection()  
                {  
                     constr =ConfigurationManager.ConnectionStrings["dbcon"].ToString();  
                     con = new SqlConnection(constr);  
          
                }  
                #endregion  
            }  
        }   
    The preceding code snippet explained everything to upload  PDF file into database , I hope you have followed the same .
     Step 6:  Create View
    Right click on View folder of the created Application and create view named Index and Partial view FileDetails , The code snippet of the view's is look like as following .
    Index.cshtml
    @{  
        ViewBag.Title = "www.compilemode.com";  
    }  
      
    @using (Html.BeginForm())  
    {  
        @Html.AntiForgeryToken()    
            <div class="form-group">  
                <div class="col-md-offset-2 col-md-10 text-success">  
                    @ViewBag.FileStatus  
                </div>  
            </div>  
      
            <div class="form-group">  
                <div class="col-md-8">  
                    @Html.Action("FileDetails", "Home")  
      
                </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>  
    FileDetails.cshtml
    @model IEnumerable<FileUploadDownLoadInMVC.Models.FileDetailsModel>  
    <table class="table table-bordered">  
        <tr>  
            <th class="col-md-4">  
                @Html.DisplayNameFor(model => model.FileName)  
            </th>  
              
            <th class="col-md-2"></th>  
        </tr>  
      
    @foreach (var item in Model) {  
        <tr>  
            <td>  
                @Html.DisplayFor(modelItem => item.FileName)  
            </td>  
              
            <td>  
                @Html.ActionLink("Downlaod", "DownLoadFile", new { id=item.Id })   
                 
            </td>  
        </tr>  
    }  
      
    </table> 
    Now, we have done all the coding.
    Step 7 - Run the Application
    After running the Application, the UI of the Application will look like as follows


    Now click on download button , then it will shows the following popup


    Choose to open or save the file , I have chosen to open the files , the contents of the files will be look like as follows


    I hope, from the preceding examples, you have learned, how to download binary formatted PDF files from database.
    Note
    • This article used dapper ORM to interact with the database. Thus, you need to install dapper ORM into the Application. If you don't know how to install dapper ORM in MVC, watch the video, using the link, given below-
    • Makes changes in web.config file connectionstring tag, based on your database location and configuration.
    • Since this is a demo, it might not be using the proper standards. Thus, improve it, depending on your skills.
    Summary
    I hope, this article is useful for all the readers. If you have any suggestions, please contact me.

    Read related article
    Don't Forget To 

      Publishing ASP.NET MVC Application Using File System

      In my previous few articles we have learned how to create ASP.NET MVC web application, Now in this article, we will learn how to publish ASP.NET MVC Applications, using File system method, Let's start step by step, so beginners can also understand.

      What is Publishing?

      Publishing is the process to make an application code suitable to host on the Server by merging multiple class codes into DLLs and by keeping only the required UI code .

      The web application goes through the following standard procedure before hosting to the Server.
      • Developing an application 
      • Publishing an application
      • Hosting an application on IIS
      Now, let's demonstrate the preceding concept step by step; i.e., how to publish ASP.NET Web MVC applications practically.

      Step 1: Create an ASP.NET MVC Application

      If you want to publish any application, first we need to create the Application. If you don't know how to create ASP.NET MVC application, Please refer to my previous articles and Video tutorials by using following links.
      Watch video which explains how to create ASP.NET MVC application step by step




      Step 2: Publish an Application

      Right click on the created ASP.NET MVC application, as shown below.


      Now, click the previously shown Publish option. It will open the Windows, mentioned below.

      Step 3: Select Publish Target

      Now, select the option, where you want to save the published code. There are lots of options given by Visual Studio to save the published code , as shown below.



      In the preceding image, we have seen that there are many options listed to publish the application, let's learn about them in brief.
      • Microsoft Azure App Service 
      This is one of the services provided by Microsoft Azure to publish the different types of the Application such as Web, REST and other into Azure (Cloud). You need a Microsoft Azure subscription to use this option.
      • Import 
      This option is used to publish the application, which is based on the predefined configuration files given by your hosting provider , which will directly publish the files in your hosting provider environment.
      • Custom
      This option is used to publish the Application into your own machine location or FTP Server, as per your most convenient way.
      • Microsoft Azure API apps 
      This option is used to publish REST API's Services in Cloud.
      • Microsoft Azure virtual machine 
      This option is used to publish the Application in Microsoft Azure virtual machine (Cloud), which requires an Azure subscription .
      There are many other options to publish the Application, using which we can publish .NET application.

      Step 4: Create Publish profile

      Now, in this article, we are going to publish an application in our local machine file system, so we need to choose custom target option. First, we need to create the profile to publish the application, so it can be a consistent setting to publish the same application in the future. Choose custom option from preceding explained target option, as shown below.


      Now, give the profile name as per your requirement and click ok. It will create the custom profile, as per your given name.

      Step 5: Choose Publish Method

      Now, configure the created profile, which decides where and how to publish the code. Select the publish method from the number of options, which are shown below.



      Now, choose the file system method from preceding methods and click Next button.

      Step 6: Choose File System Location

      Now, choose the target location of your local system in which you want to store the published code, as shown below.



      In the preceding screenshot, we have selected the target location E drive to store the published code. It may be different in your case, as per you machine, No click Next button.


      Step 7: Choose Publish code type

      Now, choose what type of code you want in production environment by choosing release or debug option, as shown below.


      Now, let's learn in brief about debug and release option.
      • Debug: Choose this option when you want to debug your application after the hosting.
      • Release: Choose this option when you do not want to debug the Application after hosting and make the application faster . 

      Step 8: Preview the configuration

      After the configuration, publish configuration tool will look like, as shown below.



      Now, click Publish option and watch the output Window, as shown below.


      Now, as shown in the preceding screenshot's highlighted section, our application code is published in our specified file system location. Now, navigate to the target folder and see the published code and files as shown below.


      Preceding is our published code, which is used to host in IIS. I hope from all the preceding examples, we learned how to publish ASP.NET MVC application in File system.

      Note

      • Choose the publish target location, as per your system.
      • Select proper publish method, as per your requirement.
      • These Publish steps are different in Visual Studio 2017

      Summary

      I hope, this article is useful for all the readers. If you have any suggestions, please contact me.

      Don't Forget To 

      Remote Validation in ASP.NET MVC

      This article explains the use of Remote attribute of Data Annotation in ASP.NET MVC with real time example, So lets learn step by step

      What is Remote Validation in ASP.NET MVC ?

      Remote is the attribute for validation in Data Annotation class which comes under System.web.mvc namespace, which is used in model class to validate records instantly. Let's demonstrate the above mentioned 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 

        www.CodeNirvana.in

        Protected by Copyscape
        Copyright © Compilemode