Click here to Skip to main content
15,123,757 members
Articles / Web Development / HTML
Posted 14 Mar 2015


27 bookmarked

Implementing AJAX in ASP.NET MVC

Rate me:
Please Sign up or sign in to vote.
4.84/5 (20 votes)
14 Mar 2015CPOL4 min read
This tip explains implementing AJAX in ASP.NET MVC.

Sample Image - maximum width is 600 pixels


This tip explains how we can implement AJAX in ASP.NET MVC. Here, I have attempted to explain the concept of partial page updates using a partial view to display product details asynchronously. For simplicity, I have stored details of three products statically in a list. The application searches the product code entered by a user and displays the corresponding product details.


Traditional web applications rely on synchronous method calls to process data. The entire web page is posted to the server each time data is submitted through the page, causing performance delays.

This problem can be overcome by using AJAX. AJAX allows web applications to call methods asynchronously. Instead of posting the entire page to the web server, only the required data is posted. This improves the overall performance of the web applications.

Using the Code

Begin by creating a new ASP.NET MVC4 project as follows:

Image 2

We will use a model class to display data in a partial view. For this, we have to add a Product class in the Models folder as follows by right clicking on the Models folder and selecting the Add Class option:

Image 3

Following is the code of the Product class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AJAXDemo.Models
    public class Product
        public string ProdCode
        public string ProdName
        public int ProdQty

Then, add new layout in the Shared folder under the Views folder as follows:

Image 4

Following is the code of the _Layout.cshtml file:

    Layout = null;

<!DOCTYPE html>

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

This layout will be used by the Index view. In this layout, the RenderSection() method defines a placeholder for the scripts section and the RenderBody() method defines a placeholder for the main content of the Index view.

Add a new controller as follows by right clicking on the Controllers folder:

Image 5

Following is the code of the Index() method:

public ActionResult Index()
   Product p1 = new Product { ProdCode = "P001", ProdName = "Mobile", ProdQty = 75 };
   Product p2 = new Product { ProdCode = "P002", ProdName = "Laptop", ProdQty = 125 };
   Product p3 = new Product { ProdCode = "P003", ProdName = "Netbook", ProdQty = 100 };
   return View();

This code creates three product objects and adds them to a static list called prodList which is declared at the class level and it renders the view associated with the Index view.

Add the view corresponding to the above action method as follows by right clicking on the Index() method in the controller:
(Note: Remember to select the layout page while adding the Index view.)

Image 6

Following is the code of the Index.cshtml view:

    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
@section scripts
    <script type="text/javascript" src="~/Scripts/jquery-1.7.1.js"></script>
    <script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.js"></script>

     new AjaxOptions
     { HttpMethod = "POST", UpdateTargetId = "div1", 
     InsertionMode = InsertionMode.Replace, LoadingElementId = "waitimage" })
<h1>Enter Product Code</h1>
    Product Code: @Html.TextBox("txtCode")<br />
    <input type="submit" value="Show Details" />
    <input type="reset" value="Clear"/>
<br />
<img id="waitimage" src="~/Images/loading42.gif" style="display:none" />
<br />
<div id="div1">

The above view references the jquery.unobtrusive-ajax.js script to implement the AJAX functionality. It also uses a div with the id "div1" to display the requested product details. It uses the Ajax.BeginForm() helper method to accept product code and submit it asynchronously. The first parameter of the Ajax.BeginForm() method specifies the name of the action method to be invoked to process the input data, the second parameter specifies the name of the controller and the third parameter specifies the AjaxOptions to be used. In the AjaxOptions, the HttpMethod property specifies the HTTP method to be used, the UpdateTargetId property specifies the ID of the div element where the partial view will be displayed, the InsertionMode property specifies the mode of insertion of the partial view, and the LoadingElemetId property specifies the ID of the image to be displayed while waiting for the asynchronous call to be completed and the view to be rendered.

The InsertionMode property can have one of the following values:

  • InsertionMode.InsertAfter - The new details are added after the existing details
  • InsertionMode.InsertBefore - The new details are added before the existing details
  • InsertionMode.Replace - The new details replace the existing details

In order to process the input and search the product code entered by the user, we add a method in the controller which returns a partial view as follows:

public PartialViewResult ShowDetails()
   string code = Request.Form["txtCode"];
   Product prod = new Product();
   foreach(Product p in prodList)
       if (p.ProdCode == code)
           prod = p;
   return PartialView("_ShowDetails", prod);

The above code searches the entered product code and returns the product corresponding to it using a partial view. It uses the Thread.Sleep() method to simulate delay in fetching the product details. This allows you to view the page loading animation while waiting for the asynchronous method call to complete.

In order to display the product details, we have to add a strongly typed partial view as follows by right clicking on the method and selecting the Add View option:

Image 7

Following is the code of the _ShowDetails view:

@model AJAXDemo.Models.Product

    <h1>Invalid Product Code</h1>
    <h1>Product Details</h1>
        Product Code: @Model.ProdCode<br />
        Product Name: @Model.ProdName<br />
        Product Quantity: @Model.ProdQty<br />

The above code displays the product details if the product code is found and the message "Invalid Product Code" if it is not found.

Before executing the application, we have to specify the routing information in the RouteConfig.cs file in the App_Start folder as follows:

                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Ajax", action = "Index", id = UrlParameter.Optional }

Also, we need to enable unobtrusive JavaScript by adding the "UnobtrusiveJavaScriptEnabled" key under the <configuration> element in the Web.config file as follows:

    <add key="webpages:Version" value="" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />

On execution, the application produces the following output:

Image 8

Entering a product code and clicking the submit button displays the corresponding product details asynchronously.

Points of Interest

AJAX is a very important feature of web applications and it provides significant performance advantage over traditional web applications.

I have developed the application using Microsoft Visual Studio Express 2013 for Web.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Azim Zahir
Instructor / Trainer NIIT, India
India India
I am a trainer by profession. Currently I am working with iFuture Technologies(India) as a Senior Faculty. I enjoy programming as a hobby. During my career I have seen the growth and decline of many technologies, many of them being my favorites like Flash, WPF, Windows Mobile Development. Few of my current favorites are Android, Xamarin and Python, though I also like traditional and evergreen languages like PHP, C#, Visual Basic and Java.

Apart from computers, my favorite pastime is bicycling.

Comments and Discussions

PraiseExcellent article! Pin
Anatot30-May-21 2:09
MemberAnatot30-May-21 2:09 
QuestionPartial View does not seem to work Pin
charles92219-Jul-17 9:30
Membercharles92219-Jul-17 9:30 
After I click "Show Details", the "Product Details" are displayed OK, but the "Enter Product Code" page is not displayed (as is shown above) nor do I see the loading42.gif. Any ideas why I'm getting that behavior? VS 2015, Windows 7, MVC 5
Questionrequest.form return always null Pin
Member 1303984322-Mar-17 21:53
MemberMember 1303984322-Mar-17 21:53 
Questionredirecting problem Pin
IndrajitDasgupat13-Sep-16 0:51
MemberIndrajitDasgupat13-Sep-16 0:51 
PraiseVery useful post, than you!!! Pin
omesur4-Aug-16 10:52
Memberomesur4-Aug-16 10:52 
Questionabout " prodList " Pin
ILYES0079-Mar-16 5:45
MemberILYES0079-Mar-16 5:45 
AnswerRe: about " prodList " Pin
ILYES0079-Mar-16 7:15
MemberILYES0079-Mar-16 7:15 
Questionajax implimentation in mvc Pin
Member 1197039828-Oct-15 2:51
MemberMember 1197039828-Oct-15 2:51 
AnswerRe: ajax implimentation in mvc Pin
AlbertoDC4-Nov-15 2:22
MemberAlbertoDC4-Nov-15 2:22 
GeneralMy vote of 5 Pin
Saleem_beig3-Sep-15 1:47
MemberSaleem_beig3-Sep-15 1:47 
QuestionVery Useful Pin
Pascualito15-Jul-15 12:07
professionalPascualito15-Jul-15 12:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.