Remote Validations in Asp.Net MVC 4 with Example

  Total Views : 2649
  Comments : 2
 
  Keywords : How to implement remote validations in asp.net mvc 4, What is remote validations in asp.net mvc with example, Remote validations in asp.net mvc with multiple additional fields example

The 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 Remotevalidations for that Open visual studio studio àGo to File à Select New àSelect Project like as shown below 

 

create new asp.net mvc project from visual studio 2012

 

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

 

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

 

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

 

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

 

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 name EmployeeDB and table with 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

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

 

Installing Entity Framework in Asp.net mvc application

 

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.

 

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 Entity framework now we are going to add ADO.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 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 Item name. Inside that you can enter any name but it must be unique and click on OK button.

 

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

 

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

 

Choose Model Content for Ado.net model in remote validations

 

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

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 User name and Password of Sql server. Last we are going to select Database Name as EmployeeDB once we done click on OK button as shown below

 

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

 

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

 

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

 

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

 

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

 

Finally click on Finish button. Here is 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 new controller (RegisterController) in asp.net mvc application Just Right click on 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 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(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 ActionResult CheckUserNameExists(string Username)

{

bool UserExists = false;

 

try

{

using (var dbcontext = newEmployeeDBEntities())

{

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 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 created CheckUserNameExists Action 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 into ADO.NET Entity Data Model (EmployeeModel.edmx) then in to 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 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>

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

 

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 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 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 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 as Razor and we are going to create a strongly type view for that we selected Model class EmployeeDetail and we want to create an input form for that I have selected Create in Scaffold template finally click on Add button. 

 

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

 

After adding 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")

}

Following are the records which we have in our database table

 

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

 

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 user exists remote validations example output in asp.net mvc application

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

 

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

 

 Comments (2)

  • sharpers tutlane registered profile image
     
    sharpers   Reply

    its working perfectly but when i do edit view remote validation there there is some isseus. Because of Remote validation i can't edit employee data without changing username.

     Aug 01, 2016
  • sharpers tutlane registered profile image
     
    sharpers   Reply

    What should i do?

     Aug 01, 2016

Leave a comment

  • Default Tutlane User