Remote Validations in ASP.NET MVC

Remote Validations in ASP.NET MVC

Sometimes, to check if a field value is valid or not, we may need to make a database call. A classic example of this is the user registration page. To register a user, we need a unique username. So, to check, if the username is not taken already, we have to make a call to the server and check the database table. RemoteAttribute is useful in situations like this. So in this article, I will discuss Remote Validations in ASP.NET MVC.

Example: When a user provides a username that already exists, the associated validation error message should be displayed immediately as shown below. 

Remote Validations in ASP.NET MVC
 

Step 1: Create Users table
Create table Users
(
  [UserID] int primary key identity,
  [FullName] nvarchar(50),
  [UserName] nvarchar(50),
  [Password] nvarchar(50) 
)

Step 2: Create one ASP.NET MVC application with the name “RemoteValidationInMVC”

Open Visual Studio and create a New project

Select File => New => Project

Remote Validations in ASP.NET MVC

After clicking on “Project” link a new dialog will pop up.

In that we are going to select web templates from the left pane after selecting web template, select “ASP.NET Web Application”.

Remote Validations in ASP.NET MVC

After selecting this project template next we are going to name the project as “RemoteValidationInMVC” and clicking on the OK button a new dialog will pop up with Name “New ASP.NET Project” for selecting project Templates.

Remote Validations in ASP.NET MVC

In this dialog, we are going to choose MVC project template and then we are going to choose Authentication type for doing that just click on Change Authentication button, a new dialog will pop up with the name “Change Authentication” here we are going to choose No Authentication click on OK Button.

It will take some to time create the project for us. Once the project is created let’s see the folder structure as shown below

Remote Validations in ASP.NET MVC

Step 3: Create an ado.net entity data model using table Users. Save and build the solution.

Remote Validations in ASP.NET MVC

It will create the following model as shown below
namespace RemoteValidationInMVC.Models
{
    public partial class User
    {
        public int UserID { get; set; }
        public string FullName { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
    }
}
Step 4: Delete the auto Generated HomeController and then add HomeController with the following settings

Template = MVC5 controller with views, using Entity Framework

Model Class = User (RemoteValidationInMVC.Models)

Data context class = UserDBContext (RemoteValidationInMVC.Models)

Controller Name = HomeController

Step 5: Copy and paste the following function in HomeController. This is the method which gets called to perform the remote validation. An AJAX request is issued to this method. If this method returns true, validation succeeds, else validation fails and the form is prevented from being submitted.

The parameter name (UserName) must match the field name on the view. If they don’t match, model binder will not be able bind the value with the parameter and validation may not work as expected.

[HttpPost]
public JsonResult IsUserNameAvailable(string UserName)
{
    return Json(!db.Users.Any(x => x.UserName == UserName),
                                         JsonRequestBehavior.AllowGet);
}

Step 6: Right click on the Models folder and a class file with name = PUser.cs. Copy and paste the following code. Notice that the name of the method (IsUserNameAvailable) and the controller name (Home) and error message are passed as arguments to Remote Attribute

Remote is the attribute for validation in Data Annotation, which is used in model class to validate records instantly.

using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
namespace RemoteValidationInMVC.Models
{
    [MetadataType(typeof(UserMetaData))]
    public partial class User
    {
    }

    public class UserMetaData
    {
        [Remote("IsUserNameAvailable", "Home",HttpMethod ="POST", ErrorMessage = "UserName already in use.")]
        public string UserName { get; set; }
    }
}

In the above example, we have defined a few properties of the Remote attribute to work on remote validation properly, let’s know them in brief.

IsUserNameAvailable: This is the JsonResult method which checks the details from the database and returns true or false.

Home: This is MVC Controller name and inside that, IsUserNameAvailable JsonResult method is defined to check the details from the 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 on the client side. 

There are many optional properties of the Remote attribute which are used as per the validation requirements.

Step 7: Include references to the following CSS and script files in Create.cshtml view.jQuery, jquery.validate and jquery.validate.unobtrusive script files are required for remote validation to work.

<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
<script src="~/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script> 
<script src="~/Scripts/jquery.validate.min.js" type="text/javascript"></script> 
<script src="~/Scripts/jquery.validate.unobtrusive.js" type="text/javascript"></script>
Step 8: Make sure ClientValidation and UnobtrusiveJavaScript are enabled in web.config

<add key=”ClientValidationEnabled” value=”true” />

<add key=”UnobtrusiveJavaScriptEnabled” value=”true” /> 

Run the application and see everything is working as expected.

Remote attribute only works when JavaScript is enabled. If the end user disables JavaScript on his/her machine then the validation does not work.

In the next article, I will discuss Remote validation in MVC when javascript is disabled

SUMMARY

In this article, I try to Remote Validations in ASP.NET MVC application step by step with some real time examples. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *