Remote Validations in Asp.Net MVC 4 with Example:-

he Remote validations in asp.net mvc is a mechanism used to make remote server call to validate specific data without posting the entire form to the server. For example Many web application require unique Username name to register to their site for checking unique Username name we are making call to server for checking in case if name already in our database means we need to show Error message "Name already Used" it is good example of Remote Validation in asp.net mvc.

For this Example let’s create a Basic asp.net Mvc 4 application with name Remote validations for that Open visual studio studio àGo to File à Select New àSelect Project like as shown below

After that you will see new dialog 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 name as “Remotevalidations” then finally click on ok button

After naming it just click on OK. After that a new dialog will popup for selecting template. in that select Basic template and click ok

After creating application now let’s work with some database part. For validating data we are going to check that data against the data which is available in database tables. For showing demo we already created a Database with nameEmployeeDBand table with nameEmployeeDetails.

EmployeeDB Database

EmployeeDetails table

Installing Entity framework

For adding Entity framework just right click on your application and from above list select “Manage NuGet Packages”.

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

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

After adding Entity framework now we are going to addADO.NET Entity Data Model

Adding ADO.NET Entity Data Model

For adding ADO.NET Entity Data Model just right click on Model folder and select Add inside that SelectADO.NET Entity Data Model.

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

After that a new Wizard will pop up like as shown below

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

Choosing Data Connection

Now click on New Connection a new Dialog will popup. Here we need to configure it. In Server name you need to add yourSql Server Nameand select eitherUsing Windows AuthenticationorUsing Sql Server Authenticationto connect SQL Server. Here we selectedUsing Sql Server Authenticationand entered User name and Password of Sql server. Last we are going to select Database Name asEmployeeDBonce we done click on OK button as shown below

After adding database connection our Entity Data Model Wizard will look like below snapshot

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

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

Adding Controller (RegisterController) in Asp.Net MVC Application

To add new controller (RegisterController) in asp.net mvc application Just Right click on Controller Folder inside that select Add and then select Controller

After adding RegisterController our project will be like as shown below

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

usingSystem;

usingSystem.Collections.Generic;

usingSystem.Linq;

usingSystem.Web;

usingSystem.Web.Mvc;

usingRemotevalidations.Models;

namespaceRemotevalidations.Controllers

{

public class RegisterController:Controller

{

[HttpGet]

public ActionResultIndex()

{

returnView(newEmployeeDetail());

}

}

}

Adding Action Method CheckUserNameExists

Now inside this Register Controller we are going to add another ActionResult with name CheckUserNameExists to validate our user name exists of not in database. The CheckUserNameExists method will take Username as input parameter and return json with Boolean flag. Your Context class is EmployeeDBEntities and table name is EmployeeDetails.

public ActionResultCheckUserNameExists(stringUsername)

{

boolUserExists =false;

try

{

using(vardbcontext =newEmployeeDBEntities())

{

varnameexits =fromtemprecindbcontext.EmployeeDetails

wheretemprec.Name.Equals(Username.Trim())

selecttemprec;

if(nameexits.Count() > 0)

{

UserExists =true;

}

else

{

UserExists =false;

}

}

returnJson(!UserExists,JsonRequestBehavior.AllowGet);

}

catch(Exception)

{

returnJson(false,JsonRequestBehavior.AllowGet);

}

}

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

Adding Attribute to Models Property

Now we have createdCheckUserNameExistsAction method 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. For finding Model we need to dig intoADO.NET Entity Data Model (EmployeeModel.edmx)then in toEmployeeModel.tthere you will see the table name or Model name EmployeeDetails.cs

Now clicking onEmployeeDetails.csclass you will see code like as shown 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>

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

namespaceRemotevalidations.Models

{

usingSystem;

usingSystem.Collections.Generic;

usingSystem.ComponentModel.DataAnnotations;

usingSystem.Web.Mvc;

public partial class EmployeeDetail

{

public intEmpID {get;set; }

public stringUserName {get;set; }

public stringName {get;set; }

public stringAddress {get;set; }

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

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

public stringworktype {get;set; }

}

}

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

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

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

public partial class EmployeeDetail

{

public intEmpID {get;set; }

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

public stringUserName {get;set; }

public stringName {get;set; }

public stringAddress {get;set; }

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

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

public stringworktype {get;set; }

}

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

Adding View

For Adding View just right click inside Index ActionResult Method and Select "Add View" to create the view template for our Index form. Here in below snapshot we selected View engine asRazorand we are going to create a strongly type view for that we selected Model classEmployeeDetailand we want to create an input form for that I have selected Create in Scaffold template finally click on Add button.

After adding view here below is a complete View ofIndex.cshtmlwhich is generated

@modelRemotevalidations.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")

}

Following are the records which we have in our database table

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

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

results matching ""

    No results matching ""