Ajax Helpers in Asp.Net MVC with Examples

  Total Views : 3746
  Comments : 0
 
  Keywords : What are the ajax helpers in asp.net mvc, How to use ajax helpers in asp.net mvc, Understand ajax helpers in asp.net mvc with examples, Ajax actionlink helpers in asp.net mvc with examples

Here we will learn what is Ajax helper in asp.net mvc and how to use Ajax helper with asp.net mvc. Let’s begin with words AJAX, AJAX stands for Asynchronous JavaScript and XML

 

In today modern era people want rich web applications for developing this kind application we need to use AJAX in one or other way. By using ajax helpers in asp.net mvc we can send data to server in asynchronous way without postbacks that will make our applications interactive, easy to use and will make end user happy.

 

By using AJAX we can update partial part of view without posting entire page to server. Here we are going to see how to use AJAX helper in asp.net mvc to submit forms and using AJAX action link to invok action method asynchronously by using JavaScript. Before starting with demo on AJAX helper let's have look on various properties of Ajax Options.

 

There might be a question what are Ajax Options?

 

These are the option settings which we need to set for running Ajax scripts in an ASP.NET MVC application

 

There are 12 properties of AjaxOptions. Below you will see Metadata of AjaxOptions class

 

Properties of ajax helpers in asp.net mvc

Let’s have look in details about all these AjaxOptions.

 

Confirm - This property display confirmation box in which you will see ok and cancel button if you click on ok button after that Ajax request is made. This confirmation box is displayed before making AJAX request.

 

HttpMethod - This property is used while making Ajax request which are GET or POST by default this value is set to POST.

 

InsertionMode - There are 3 insertion modes ("InsertAfter", "InsertBefore", "Replace"). The default value is "Replace”. This specifies the way in which the data response will be retrieved from server is inserted into the target DOM element.

 

LoadingElementId - While AJAX request is processing if we want to display Progress bar or Loader then we can use this Property.

 

LoadingElementDuration - By setting this property we can control duration of LoadingElementId (Progress bar or Loader duration) for how much time it must be displayed.

 

UpdateTargetId - By setting UpdateTargetId of HTML elements the data from server will be added to this HTML element.

 

Url - which controllers Action Method to be called on while making Ajax Request is set here.

 

OnBegin - This AjaxOptions is called before sending Ajax call.

 

OnComplete - This AjaxOptions is called when Ajax call completed.

 

OnFailure - this AjaxOptions is called when Ajax call fails.

 

OnSuccess - This AjaxOptions is Ajax request completes successfully and happens before OnComplete.

 

After understanding now let’s move forward for creating application in asp.net mvc and add AJAX functionally to it. We are going to create basic form and submit form in AJAX way and implementing all AjaxOptions in it.

Create New Asp.Net MVC Application

Let's start with creating new asp.net mvc 4 application for that Open visual studio studio à Go to File à Select New à Select Project

 

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 “Tutorial14” then finally click on OK button

 

select asp.net mvc 4 web application and click ok to create new mvc application

 

After naming and click on OK button now new dialog will pop up for selecting template in that Select Basic template and set view engine as Razor and we are not going to create Unit testing for this project hence do not check this option and finally click OK like as shown below

 

select asp.net mvc project template type in ajax helpers example

 

 After selecting all option now click OK button our Project will create like as shown below.

 

asp.net mvc application structure for ajax helpers methods

 

After creating project now let’s add Model with name Countries. To add new model file open Solution Explorer à right click the Models folder à Select Add à then select Class. Now give name to the class as Countries and finally click on Add button to create Model. Once we finish adding new model file that will be like as shown below.

 

Add new model file in asp.net mvc ajax helpers example

 

Now open countries model file and add properties like as shown below.

 

publicclassCountries

{

[Key]

public int CountriesID { get; set; }

public string CountriesName { get; set; }

}

After adding Countries Model now we are going to use Code First Approach for accessing database for that we are going to add class DbconnectionContext which will be inheriting from DbContext.

 

Adding Context class

 

For adding context class In Solution Explorer, right click the Models folder à Select Add à then select Class à Name the class DbconnectionContext. After adding class that will be like as shown below

 

after adding dbcontext class file in asp.net mvc application

 

Now open class DbconnectionContext file and Inherit from DbContext Class after this step in DbconnectionContext constructor we are going call base class (DbconnectionContext) and Provide Connection String in it.

 

using System;

using System.Collections.Generic;

using System.Data.Entity;

using System.Linq;

using System.Web;

 

namespace Tutorial14.Models

{

public class DbconnectionContext : DbContext

{

public DbconnectionContext()

: base("DefaultConnection")

{

 

}

public DbSet<Countries> Countries { get; set; }

}

}

Now we will add connection string in web.config because we need to tell it where to create Database.

 

<connectionStrings>

<add name="DefaultConnectionproviderName "System.Data.SqlClientconnectionString="data source=SAI-PC; initial catalog=OrderDB; persist security info=True; user id=sa; password=Pass$123; App=EntityFramework" />

</connectionStrings>

After completion of database part now let’s move towards adding Controller.

Adding New Controller in Asp.Net MVC

To add controller just right click on Controller folder then select Add from list and inside that select controller.

 

Add new controller in asp.net mvc ajax helpers application

 

 After selecting controller a new dialog will pop up with name Add Controller like as shown below.

 

Give name to new controller in asp.net mvc ajax helpers example

 

Now let’s name of controller to HomeController and in template we are going to select Empty MVC controller. Finally click on Add button to Create HomeController. Once we add controller that will contain code like as shown below.

 

Home controller with source code in asp.net mvc ajax helpers

 

After adding HomeController you will see Index Action Method created by default. Now let’s add 2 Action Method with name AddCountries this action method we are going to call using AjaxOptions.

 

[HttpPost]

public ActionResult AddCountries(Countries objCountries)

{

if (Request.IsAjaxRequest())

{

using (DbconnectionContext obj = newDbconnectionContext())

{

obj.Countries.Add(objCountries);

obj.SaveChanges();

}

}

return View();

}

 

[HttpGet]

public ActionResult AddCountries()

{

return View();

}

After adding Action Method now it’s time to add View.

Adding New View in Asp.Net MVC Application

For Adding View Just right click inside Controller Action Method (AddCountries) then select option Add View like as shown below.

 

Add new view in asp.net mvc for controller method in ajax helpers method

 

After selecting Add View option a New Wizard will pop up with Name (Add View). It will have View Name Same name as Action Method inside which you right click to add View. In this example we are going to create Strongly - Typed view for that we check this option and in Model class we selected Countries model class.

 

give name to new view in asp.net mvc ajax helpers

 

After selecting required option now finally click on Add button. After that a View will be created inside Views folder and in that we will have folder with name of controller inside that our view will be created. Following is the code snippet of our newly created view.

 

@model Tutorial14.Models.Countries

@{

Layout = null;

}

<!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width"/>

<title>AddCountries</title>

</head>

<body>

<script src="~/Scripts/jquery-1.7.1.min.js"></script>

<script src="~/Scripts/jquery.validate.min.js"></script>

<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

@using (Html.BeginForm())

{

@Html.ValidationSummary(true)

<fieldset>

<legend>Countries</legend>

<div class="editor-label">

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

</div>

<div class="editor-field">

@Html.EditorFor(model => model.CountriesName)

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

</div>

<p>

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

</p>

</fieldset>

}

<div>

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

</div>

</body>

</html>

Now save your application and RUN then access URL like "http://localhost:####/home/AddCountries" that will be like as shown below.

 

Add new countries screen in asp.net mvc ajax helpers application

 

Just enter Countries Name and click on Create button as you click it will create a database with name OrderDB and inside that will create table because we are using Code first approach of Entity framework. Follwing is database OrderDB which is created after running Application (Code First).

 

Created new database in asp.net mvc ajax helpers application

 

Following is the table which is created [Countries].

 

countries table in new database in asp.net mvc ajax helpers methods

After that while adding countries you might have seen page flickers. This effect is due to entire page is posted to server. Now let’s make a form Ajaxified. 

Adding AJAX features in Asp.Net MVC Application

First thing we are going to add AjaxOptions in asp.net mvc application. Here we are going to set 6 AjaxOptions and to post form to server we assigned HttpMethod to "POST". And all remaining AjaxOptions are assigned with JavaScript function you can see following code snippet it will give idea of it.

 

@{

AjaxOptions options = new AjaxOptions();

options.HttpMethod = "POST";

options.OnBegin = "OnBeginRequest";

options.OnSuccess = "OnSuccessRequest";

options.OnComplete = "OnCompleteRequest";

options.OnFailure = "OnFailureRequest";

options.Confirm = "Do you want to Add Country ?";

}

After adding Ajax options now we are going to create JavaScript function for assign to AjaxOptions.

 

<script type="text/javascript">

function OnBeginRequest() {

alert('On Begin');

}

function OnCompleteRequest() {

alert('On Completed');

}

function OnSuccessRequest() {

alert('On Success');

}

function OnFailureRequest() {

alert('On Failure');

}

</script>

After adding Function now let’s make changes in form tag of AddCountries view. We are going to modify form tag as given below.

 

Normal Tag

 

@using (Html.BeginForm("AddCountries", "Home"))

{

 

}

Ajax Form tag

 

In Ajax form tag we need to pass AjaxOptions in which we have assign JavaScript function. 

 

@using (Ajax.BeginForm ("AddCountries", "Home", options))

{

 

}

Following is the complete Markup of AddCountries view after adding Ajax options.

 

@model Tutorial14.Models.Countries

@{

Layout = null;

}

<!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width"/>

<title>AddCountries</title>

</head>

<body>

<script src="~/Scripts/jquery-1.7.1.min.js"></script>

<script src="~/Scripts/jquery.validate.min.js"></script>

<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

<script type="text/javascript">

function OnBeginRequest() {

alert('On Begin');

}

function OnCompleteRequest() {

alert('On Completed');

}

function OnSuccessRequest() {

alert('On Success');

}

function OnFailureRequest() {

alert('On Failure');

}

</script>

 

@{

AjaxOptions options = new AjaxOptions();

options.HttpMethod = "POST";

options.OnBegin = "OnBeginRequest";

options.OnSuccess = "OnSuccessRequest";

options.OnComplete = "OnCompleteRequest";

options.OnFailure = "OnFailureRequest";

options.Confirm = "Do you want to Add Country ?";

}

 

@using (Ajax.BeginForm("AddCountries", "Home", options))

{

@Html.ValidationSummary(true)

<fieldset>

<legend>Countries</legend>

<div class="editor-label">

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

</div>

<div class="editor-field">

@Html.EditorFor(model => model.CountriesName)

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

</div>

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

</fieldset>

}

</body>

</html>

After making changes in AddCountries views now save your application and run then access URL like "http://localhost:####/home/AddCountries".

 

Add new countries screen in asp.net mvc ajax helpers application

 

Let’s enter a Countries name and click on Create button when we click on Create button the page started post backing the Action Method is not getting called. This is happening because we didn't added Unobtrusive Ajax reference to page without adding Unobtrusive Ajax we cannot use Ajax helper in asp.net mvc.

 

script folder with jquery unobstrusive ajax in asp.net mvc ajax helper methods

 

You may have a question what is Unobtrusive Ajax?

 

Unobtrusive Ajax is way of separating JavaScript and Ajax from HTML Markup such that we can keep them clean, organize and easy for maintenance.

 

Example - if we are using any date picker on page then we will add whole lot of Ajax and JavaScript code on that page and make that page bulky. If we use Unobtrusive Ajax and JavaScript then we are just going to add reference to this file on Page and not going to write or render any JavaScript and Ajax on page.

 

Let’s come back for adding Unobtrusive Ajax reference to page in asp.net mvc

 

Adding unobstrusive jquery file in asp.net mvc ajax helpers method

 

Now to handle the request we need to add "UnobtrusiveJavaScriptEnabled" as a key in the web.config file under the "<appSettings>" section like as shown below

 

<appSettings>

<add key="webpages:Versionvalue="2.0.0.0" />

<add key="webpages:Enabledvalue="false" />

<add key="PreserveLoginUrlvalue="true" />

<add key="ClientValidationEnabledvalue="true" />

<add key="UnobtrusiveJavaScriptEnabledvalue="true" />

</appSettings>

After adding these now save your application and RUN. 

Ajax Confirm message in Asp.Net MVC

After running application just enter Countries Name and click on Create button. The First Message will pop up which is Confirmation below is AjaxOptions which we have set.

 

Ajax helper method confirm in asp.net mvc application

 

Following is the way we need to set Confirm ajax helper option in asp.net mvc

 

Ajax helper method options in asp.net mvc application

Ajax OnBegin message in Asp.Net MVC

The second message will pop up which is OnBegin below is the AjaxOptions which we have set.

 

Ajax OnBegin helper method message in asp.net mvc application

 

Following is the way we need to set OnBegin ajax helper option in asp.net mvc

 

Ajax Options OnBegin Helper Method in Asp.Net MVC

Ajax OnSuccess message in Asp.Net MVC

The Third Message will pop up which is On Success below is AjaxOptions which we have set.

 

Ajax onSuccess Helper Method in Asp.net MVC Application

 

Following is the way we need to set ajax onSuccess helper option in asp.net mvc.

 

set onSuccess ajax helper option in asp.net mvc application

Ajax OnComplete Option Message in Asp.Net MVC

The fourth message will pop up which is OnComplete below is AjaxOptions which we have set.

 

Ajax oncomplete helper option in asp.net mvc application

 

Following is the way we will set ajax oncomplete method in asp.net mvc

set ajax oncomplete helper method option in asp.net mvc application

Let’s add some more Ajax options add Loader progress images as we submit form and should get hide as we complete process request.

Setting up Ajax Loading Image in Asp.Net MVC

We are going to set following Ajax options to display Ajax Loading images

Set up ajax loading image while submitting page request in asp.net mvc application

 First step is to setup ajax loading image we need to add a div and inside that a loader gif image like as shown below code

 

<div id="divProgress" style="display: none;">

<div class="modalBackground ajax-loader">

<img src="~/Images/ajax-loader.gif"/>

</div>

</div>

Second step is to set LoadingElementId which will be the div id (divProgress) which we have recently added.

 

options.LoadingElementId = "divProgress";

Third step is to set LoadingElementDuration which is in milliseconds.

 

options.LoadingElementDuration = 1000;

Generally LoadingElementDuration property gets or sets a value, in milliseconds, that controls the duration of the animation when showing or hiding the loading. As per show below 1 second equals to 1000 milliseconds

 

convert second to millisecond in asp.net mvc ajax helpers application

 

Fourth step is to set UpdateTargetId which will be the div id (divResponse) in which we want server data to be added when we get in response.

 

<div id="divResponse">

</div>

Following is the ajax option we added to access this targedid

 

 options.UpdateTargetId = "divResponse";

Fifth step is to set InsertionMode we are going to set it to replace.

 

options.InsertionMode = InsertionMode.Replace;

Adding Partial View in Asp.Net MVC Application

Now let’s add a partial view to AddCountries Action Method in Home Controller. For adding Partial View just right click inside Action Method AddCountries and then select Add View Option after that Add View dialog will pop up then we are going to name View as “_Message” and after that going to check Create as a partial view options and finally click on Add button.

 

Adding partial view in asp.net mvc ajax helpers example

 

After adding it will get added in Home folder which is inside Views Folder like as shown below

 

After adding partial view asp.net mvc ajax helpers project structure

 

Now let’s add some mark up inside “_Message” partial view like as shown below

 

@{

Layout = null;

}

<!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width"/>

<title>Add Countries</title>

</head>

<body>

<div>

<h3>Data Added Successfully </h3>

</div>

</body>

</html>

And in last step I am going to change return type of AddCountries Action Method from return View(); to return PartialView ("_Message");

 

[HttpPost]

public ActionResult AddCountries(Countries objCountries)

{

if (Request.IsAjaxRequest())

{

using (DbconnectionContext obj = new DbconnectionContext())

{

obj.Countries.Add(objCountries);

obj.SaveChanges();

}

}

return PartialView("_Message");

}

Now save and run application with url like "http://localhost:####/home/AddCountries". After running application access your AddCountries page and there enter Countries Name and click on Create button as you click you will see Loader progress image and after completing request it will get hided and then your partial view message will be displayed there.

showing loading progress image while processing in asp.net mvc ajax helper methods

 

Following is the partial view which is displayed after adding data

 

Displaying Partial view after adding data in asp.net mvc ajax helpers example

 

If we check table Countries in which we can find records whatever we created from asp.net mvc ajax helpers application like as shown below

 

countries table in new database in asp.net mvc ajax helpers methods

After completion of submitting form using Ajax now let’s work with Ajax ActionLink (@Ajax.ActionLink) to get data from database and insert the response in html container.

How to Use Ajax ActionLink helper in Asp.Net MVC?

The Ajax ActionLink (@Ajax.ActionLink) is similar to html ActionLink (@Html.ActionLink) but Ajax ActionLink send asynchronous request to Action Method and the response of this action Method can be used to update html elements ( UpdateTargetId = "divResponse") .

 

Let’s start with example for this we added new Action Method with Name ViewCountry in Home Controller which returns List of Countries which we added.

 

public ActionResult ViewCountry()

{

using (DbconnectionContext db = new DbconnectionContext())

{

List<Countries> list = db.Countries.ToList();

return PartialView("_CountryList", list);

}

}

Adding Partial View for ViewCountry Method

Let's add a Partial view to this ViewCountry Action Method. For adding Partial view just right click in side Action Method then select Add View from list a new dialog of Add View will popup then Enter View name “_CountryList” after that select as View engine (Razor) and we are going to create a strongly type view for that we are going to check this option and in Model class we are going to select Countries Model after selecting this we are going keep Scaffolding template to Empty.

 

Adding new view to show countries details in asp.net mvc ajax helper application

 

After adding Partial View it will get added to Home Folder in View

 

After adding view in asp.net mvc ajax helpers application

 

If you open this partial view you will see empty View with tightly coupled Countries Model. Here we will modify tightly coupled Model to take IEnumerable list as input and using Foreach loop for displaying data from collection one by one.

 

@model IEnumerable<Tutorial14.Models.Countries>

<table>

<tr>

<th>Countries ID</th>

</tr>

<tr>

<th>Countries Name</th>

</tr>

@foreach (var item in Model)

{

<tr>

<td>

@Html.DisplayFor(modelItem => item.CountriesID)

</td>

<td>

@Html.DisplayFor(modelItem => item.CountriesName)

</td>

</tr>

}

</table>

Adding another group of Ajax options for Ajax Action Link.

 

@{

AjaxOptions objAjaxOptions = new AjaxOptions();

objAjaxOptions.HttpMethod = "POST";

objAjaxOptions.UpdateTargetId = "divshowResponse";

objAjaxOptions.InsertionMode = InsertionMode.Replace;

objAjaxOptions.LoadingElementId = "divProgress";

}

 

After adding Ajax options now we are going to add Ajax Action Link and pass this Ajax option to this helper method. Here we are going to Add Ajax ActionLink (@Ajax.ActionLink) to your Main page (AddCountries) view it is similar as we configured @Ajax.BeginForm helper.

 

@Ajax.ActionLink("Show Countries Data", "ViewCountry", "Home", objAjaxOptions)

Following is the detailed explanation of ajax actionlink

Detailed explanation of ajax actionlink in asp.net mvc

 

Now we will add divProgress html element which is used for display loading image when we click on ActionLink (LoadingElementId) for display loading image while it load data from server.

 

<div id="divProgress" style="display: none;">

<div class="modalBackground ajax-loader">

<img src="~/Images/ajax-loader.gif"/>

</div>

</div>

Now we are going to add Html Element in which we are going populate data to receive as Response from server.

 

<div id="divshowResponse">

</div>

After adding html Elements now let’s have look on complete markup of AddCountries view how it look.

 

@model Tutorial14.Models.Countries

@{

Layout = null;

}

<!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width"/>

<title>AddCountries</title>

<script src="~/Scripts/jquery-1.7.1.min.js"></script>

<script src="~/Scripts/jquery.validate.min.js"></script>

<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>

<script type="text/javascript">

function OnBeginRequest() {

alert('On Begin');

$("#divResponse").empty();

}

function OnCompleteRequest() {

alert('On Completed');

}

function OnSuccessRequest() {

alert('On Success');

}

function OnFailureRequest() {

alert('On Failure');

}

</script>

</head>

<body>

@{

AjaxOptions options = new AjaxOptions();

options.HttpMethod = "POST";

options.OnBegin = "OnBeginRequest";

options.OnSuccess = "OnSuccessRequest";

options.OnComplete = "OnCompleteRequest";

options.OnFailure = "OnFailureRequest";

options.Confirm = "Do you want to Add Country ?";

options.LoadingElementId = "divProgress";

options.LoadingElementDuration = 1000;

options.UpdateTargetId = "divResponse";

options.InsertionMode = InsertionMode.Replace;

}

<div id="divResponse">

</div>

@using (Ajax.BeginForm("AddCountries", "Home", options))

{

@Html.ValidationSummary(true)

<fieldset>

<legend>Countries</legend>

<div class="editor-label">

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

</div>

<div class="editor-field">

@Html.EditorFor(model => model.CountriesName)

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

</div>

<p>

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

</p>

</fieldset>

}

 

@*--------------------------------------------------------------------------*@

 

@{

AjaxOptions objAjaxOptions = new AjaxOptions();

objAjaxOptions.HttpMethod = "POST";

objAjaxOptions.UpdateTargetId = "divshowResponse";

objAjaxOptions.InsertionMode = InsertionMode.Replace;

objAjaxOptions.LoadingElementId = "divProgress";

}

<br/>

Ajax ActionLink :-

@Ajax.ActionLink("Show Countries Data", "ViewCountry", "Home", objAjaxOptions)

<div id="divshowResponse">

</div>

<div id="divProgress" style="display: none;">

<div class="modalBackground ajax-loader">

<img src="~/Images/ajax-loader.gif"/>

</div>

</div>

</body>

</html>

Following is complete code snippet of Home Controller.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using Tutorial14.Models;

 

namespace Tutorial14.Controllers

{

public class HomeController : Controller

{

public ActionResult Index()

{

using (DbconnectionContext obj = new DbconnectionContext())

{

List<Countries> Countries = obj.Countries.ToList();

}

return View();

}

[HttpPost]

public ActionResult AddCountries(Countries objCountries)

{

if (Request.IsAjaxRequest())

{

using (DbconnectionContext obj = new DbconnectionContext())

{

obj.Countries.Add(objCountries);

obj.SaveChanges();

}

}

return PartialView("_Message");

}

public ActionResult ViewCountry()

{

using (DbconnectionContext db = new DbconnectionContext())

{

List<Countries> list = db.Countries.ToList();

return PartialView("_CountryList", list);

}

}

[HttpGet]

public ActionResult AddCountries()

{

return View();

}

}

}

Now save Application and RUN then Access View AddCountries which is under Home Controller.  After rendering AddCountries view it displaying Ajax ActionLink.

 

Displaying ActionLink (Show Countries Data) on AddCountries View

 

After click on Ajax ActionLink it is going to Call (ViewCountry) Action Method. In ViewCountry Action Method we are going to return Partial View and that Partial View data is getting Updated in Html element (“divshowResponse”).

 

Displaying Data after Clicking on ActionLink (Show Countries Data).

 

Finally we completed learning Ajax Helpers in asp.net mvc with examples.

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User