Loading

ASP.NET MVC

How to apply Remote Validations in ASP.NET MVC?. The Complete ASP.NET MVC Developer Course 2023 [Videos].

In this article, I am going to discuss Remote Validations in ASP.NET MVC applications. Please read our previous article where we discussed Validation Message and Validation Summary Attribute in ASP.NET MVC Application. At the end of this article, you will understand what is Remote Validation and why we need this and how to implement Remote Validations in ASP.NET MVC applications.

What is Remote Validation in ASP.NET MVC Application?

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 Gmail 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 Video, I am going to discuss how to use Remote Validations in ASP.NET MVC Application.

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)
)

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

Step3: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

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; }
}
}
Step4: Add HomeController with the following settings
  1. Template = MVC5 controller with views, using Entity Framework
  2. Model Class = User (RemoteValidationInMVC.Models)
  3. Data context class = UserDBContext (RemoteValidationInMVC.Models)
  4. Controller Name = HomeController
Step5: 

Copy and paste the following function in HomeController. This is the method that 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 dont match, the model binder will not be able to 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);
}
Step6:

Right-click on the Models folder and a class file with the name PUser.cs. Copy and paste the following code. Notice that the name of the method (IsUserNameAvailable) and the controller name (Home) and the 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, lets know them in brief.

  1. IsUserNameAvailableThis is the JsonResult method which checks the details from the database and returns true or false.
  2. HomeThis is the MVC Controller name and inside that, the IsUserNameAvailable JsonResult method is defined to check the details from the database.
  3. HttpMethodThis is the HttpMethod type which is called on Remote attribute e.g. Get, Put, Post. This is optional to define.
  4. ErrorMessageThis 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.

Step7:

Include references to the following CSS and script files in Create.cshtml view. 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>
Step8:

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. The remote attribute only works when JavaScript is enabled. If the end-user disables JavaScript on his/her machine then the validation does not work. 

See All

Comments (303 Comments)

Submit Your Comment

See All Posts

Related Posts

ASP.NET MVC / Youtube

What is MVC?

MVC is an architectural software design pattern that is used for developing interactive applications where their user interaction is involved and based on the user interaction some event handling has occurred. It is not only used for web-based applications but it can also be used for Desktop or mobile-based applications where there are user interactions involved.
28-jan-2022 /28 /303

ASP.NET MVC / Youtube

How to Creat First ASP.NET MVC Application using Visual Studio?

In this article, I am going to discuss how to create the first ASP.NET MVC Application step by step from scratch using Visual Studio 2015. You can use any version as per your choice but the step will remain the same. Please read our previous article before proceeding to this article where we gave a brief introduction to ASP.NET MVC Framework.
28-jan-2022 /28 /303

ASP.NET MVC / Youtube

What is ASP.NET MVC File and Folder Structure?

In this article, I am going to discuss the auto-generated ASP.NET MVC File and File Structure when we create a new ASP.NET MVC application. Please read our previous article before proceeding to this article where we discussed how to create ASP.NET MVC 5 application step by step from scratch.
28-jan-2022 /28 /303