Remote Validations in Asp.Net MVC 4 with Example

The Remote validations in asp.net mvc is a mechanism used to make a remote server call to validate specific data without posting the entire form to the server. For example, many web application requires a unique Username name to register to their site. To check the unique Username name, we are making calls to the server to check whether the username exists or not, and we need to show the Error message "Name already Used" if not exist. It is a good example of Remote Validation in asp.net mvc. 

 

For this example, let’s create a basic asp.net MVC 4 application with the name Remotevalidations for that Open visual studio à Go to File à Select New à Select Project as shown below.

 

create new asp.net mvc project from visual studio 2012

 

After that, you will see a new dialog that will pop up for selecting your Template and Project type. From Templates select Visual C# àinside that select Web and then project type select ASP.NET MVC 4 Web Application and here we are giving the name as “Remotevalidations” then finally click on ok button.

 

give name of project as remotevalidations in asp.net mvc application

 

After naming it, click on OK, a new dialog will popup for selecting the template. In that, choose the Basic template and click ok.

 

select basic template to create new application in asp.net mvc

 

After creating the application now, let’s work with some database part. To validate data, we need to validate the data against the available data in database tables. For showing the demo, we already created a Database with the name EmployeeDB and a table with the name EmployeeDetails.

EmployeeDB Database

Employeedb database in asp.net mvc application for remote validations

EmployeeDetails table

Employee Details Table in Employeedb database

Installing Entity framework

To add the Entity framework, right-click on your application and select “Manage NuGet Packages” from the above list.

 

Installing Entity Framework in Asp.net mvc application

 

After selecting the Manage NuGet Packages option, a new dialog will popup of “Manage NuGet Packages”. Inside the search box, enter “EntityFramework”. After getting the search value, select EntityFramework click on the install button.

 

Installing Entity Framework in Asp.net mvc application

 

After adding it will show an ok sign in green color.

 

After install entity framework in asp.net mvc application

 

After adding the Entity framework, we will add ADO.NET Entity Data Model.

Adding ADO.NET Entity Data Model

For adding ADO.NET Entity Data Model, right-click on the Model folder and select Add inside that Select ADO.NET Entity Data Model.

 

Adding ado.net entity data model in asp.net mvc applciation

 

After clicking on ADO.NET Entity Data Model, a New Dialog will pop up for entering the Item name. Inside that, you can enter any name, but it must be unique and click on the OK button.

 

Give name to employee model for data entity in asp.net mvc application

 

After that, a new Wizard will pop up, as shown below.

 

Choose Model Content for Ado.net model in remote validations

 

From that, select Generate from the database and click on the Next button. After clicking on the Next button, a New Wizard will pop up for Choosing Data Connection.

Choosing Data Connection

Choose new database connection in remote validations example

 

Now click on New Connection a new Dialog will popup. Here we need to configure it. In Server name, you need to add your SQL Server Name and select either Using Windows Authentication or Using SQL Server Authentication to connect SQL Server. Here we selected Using SQL Server Authentication and entered the User name and Password of the SQL server. Last, we will select Database Name as EmployeeDB and click on the OK button as shown below.

 

configure database connection in repository pattern in asp.net mvc application

 

After adding a database connection, our Entity Data Model Wizard will look like the below snapshot.

 

Choose create data connection database in repository validations asp.net mvc application

 

Now click on the Next button. A new wizard will pop up for selecting database objects, and in this, you will see all the tables we have created in the database.

 

select database table from database in ado.net entity framework in asp.net mvc

 

Finally, click on the Finish button. Here is a snapshot after adding ADO.NET Entity Data Model.

 

After adding ado.net connection in asp.net mvc application

Adding Controller (RegisterController) in Asp.Net MVC Application

To add a new controller (RegisterController) in asp.net mvc application, right-click on the Controller folder inside that select Add and then select Controller.

 

Adding new controller in asp.net mvc remote validations application

 

After adding RegisterController, our project will be like as shown below.

 

asp.net mvc remote validations project structure after adding controller

 

After adding Controller, some default code will be generated in RegisterController that will be like as shown below.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using Remotevalidations.Models;

 

namespace Remotevalidations.Controllers

{

public class RegisterController : Controller

{

[HttpGet]

public ActionResult Index()

{

return View(new EmployeeDetail());

}

}

}

Adding Action Method CheckUserNameExists

Now inside this Register controller, we will add another ActionResult with the name CheckUserNameExists to validate whether our user name exists or not in the database. The CheckUserNameExists method will take Username as input parameter and return JSON with the Boolean flag. Your Context class is EmployeeDBEntities, and the table name is EmployeeDetails.

 

public ActionResult CheckUserNameExists(string Username)

{

bool UserExists = false;

 

try

{

using (var dbcontext = new EmployeeDBEntities())

{

var nameexits = from temprec in dbcontext.EmployeeDetails

where temprec.Name.Equals(Username.Trim())

select temprec;

if (nameexits.Count() > 0)

{

UserExists = true;

}

else

{

UserExists = false;

}

}

return Json(!UserExists, JsonRequestBehavior.AllowGet);

}

catch (Exception)

{

return Json(false, JsonRequestBehavior.AllowGet);

}

}

Inside this Action method, we wrote a simple Linq query to check username which is coming as input to this action Method is already exists in the database or not. By checking the count of records, if a username exists, its count will be greater than zero, it will return true, or if not greater than zero, return false.

Adding Attribute to Models Property

We have created the CheckUserNameExists Action method, and it’s time to call this method. To call this method, we need to add Attribute to Models Property, where we want to call this validate method. To find the Model, we need to dig into ADO.NET Entity Data Model (EmployeeModel.edmx) then into EmployeeModel.tt here you will see the table name or Model name EmployeeDetails.cs

 

open edmx file to add action method to check username exists in remote validations asp.net mvc applicaiton

 

Now clicking on EmployeeDetails.cs class, you will see code like below.

 

//------------------------------------------------------------------------------

// <auto-generated>

//    This code was generated from a template.

//

//    Manual changes to this file may cause unexpected behavior in your application.

//    Manual changes to this file will be overwritten if the code is regenerated.

// </auto-generated>

//------------------------------------------------------------------------------

 

namespace Remotevalidations.Models

{

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.Web.Mvc;

 

public partial class EmployeeDetail

{

 

public int EmpID { get; set; }

public string UserName { get; set; }

public string Name { get; set; }

public string Address { get; set; }

public Nullable<int> Age { get; set; }

public Nullable<decimal> Salary { get; set; }

public string worktype { get; set; }

}

}

In this model class, we need to call validation on the Username property. For adding that Remote validation, we need to add this attribute to the property.

 

[Remote("Action name", "Controller", ErrorMessage = "Error Message")]

 

Here is the model after adding Remote validation action and Method Name will be CheckUserNameExists and Controller name "Register" as shown below.

 

public partial class EmployeeDetail

{

 

public int EmpID { get; set; }

[Remote("CheckUserNameExists", "Register", ErrorMessage = "UserName already exists!")]

public string UserName { get; set; }

public string Name { get; set; }

public string Address { get; set; }

public Nullable<int> Age { get; set; }

public Nullable<decimal> Salary { get; set; }

public string worktype { get; set; }

 

}

Now after completing with Model work now, let’s add a View.

Adding View

For Adding View, right-click inside Index ActionResult Method and Select "Add View" to create the view template for our Index form. Here in the below snapshot, we selected View engine as Razor, and we are going to create a strong type view for that we selected Model class EmployeeDetail. We want to create an input form so that we have selected Create in Scaffold template and finally click on the Add button.

 

Adding view to controller by right click in asp.net mvc application

 

After adding the view, here below is a complete View of Index.cshtml, which is generated.

 

@model Remotevalidations.Models.EmployeeDetail

@{

ViewBag.Title = "Index";

}

<h2>Index</h2>

@using (Html.BeginForm()) {

@Html.ValidationSummary(true)

<fieldset>

<legend>EmployeeDetail</legend>

<div class="editor-label">

@Html.LabelFor(model => model.EmpID)

</div>

<div class="editor-field">

@Html.TextBoxFor(model => model.EmpID)

@Html.ValidationMessageFor(model => model.EmpID)

</div>

<div class="editor-label">

@Html.LabelFor(model => model.UserName)

</div>

<div class="editor-field">

@Html.TextBoxFor(model => model.UserName)

@Html.ValidationMessageFor(model => model.UserName)

</div>

<div class="editor-label">

@Html.LabelFor(model => model.Name)

</div>

<div class="editor-field">

@Html.TextBoxFor(model => model.Name)

@Html.ValidationMessageFor(model => model.Name)

</div>

<div class="editor-label">

@Html.LabelFor(model => model.Address)

</div>

<div class="editor-field">

@Html.TextBoxFor(model => model.Address)

@Html.ValidationMessageFor(model => model.Address)

</div>

<div class="editor-label">

@Html.LabelFor(model => model.Age)

</div>

<div class="editor-field">

@Html.TextBoxFor(model => model.Age)

@Html.ValidationMessageFor(model => model.Age)

</div>

<div class="editor-label">

@Html.LabelFor(model => model.Salary)

</div>

<div class="editor-field">

@Html.TextBoxFor(model => model.Salary)

@Html.ValidationMessageFor(model => model.Salary)

</div>

<div class="editor-label">

@Html.LabelFor(model => model.worktype)

</div>

<div class="editor-field">

@Html.TextBoxFor(model => model.worktype)

@Html.ValidationMessageFor(model => model.worktype)

</div>

<p>

<input type="submit" value="Create"/>

</p>

</fieldset>

}

<div>

@Html.ActionLink("Back to List", "Index")

</div>

@section Scripts {

@Scripts.Render("~/bundles/jqueryval")

}

The following are the records that we have in our database table.

 

User details table with data in remote validations asp.net mvc application

 

Now run the application and access the page by entering URL: - http://localhost:#####/Register/index. In case if UserName exists in the database following is the output of the asp.net mvc remote validations example.

 

in case if user exists remote validations example output in asp.net mvc application

 

In case if UserName does not exist in the database, the following is the output of the asp.net mvc remote validations example.

 

in case if user not exists remote validations example output in asp.net mvc application