jQuery Unobtrusive AJAX For Partial Updates In ASP.NET MVC

In this article, you will learn
  1. What is @Ajax.ActionLink
  2. How does this work?
  3. How to add MicrosoftMvcAjax.js & MicrosoftAjax.js in MVC Project.
  4. Add a loading image while loading data.
  5. How to update a div content using @Ajax.ActionLink
Ajax.ActionLink is much like the Html.ActionLink counterpart. It also creates the hyperlink <a href="">Click here</a> but when the user clicks it and has a JavaScript enabled browser, Ajax.ActionLink sends the asynchronous request instead of navigating to the new URL. With the Ajax.ActionLink, we specify what controller's action method is to be invoked and also specify what to do with the response coming back from the action method.
 
Ajax.ActionLink creates a hyperlink in the browser
  1. <a class="btn btn-success" data-ajax="true" data-ajax-begin="onAjaxBegin" data-ajax-complete="onAjaxComplete" data-ajax-loading="#divLoading" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#UpdateContentDiv" href="">List Data</a>   
Let's create an Ajax.ActionLink helper that will send an asynchronous request to the action method and will update the DOM with the result. 

 

Let's create an MVC Project. If you don't know how to create a simple MVC Project, refer to my previous blogs.

Once you have successfully created a MVC Project, we need to make sure that we have added reference to jquery.unobtrusive-ajax.js and
jquery.validate.unobtrusive.js in your project.

First, let's add jquery.unobtrusive-ajax.js and jquery.validate.unobtrusive.js in your project. The step is very simple. You can use Nuget Package Manager to install these files or you can do it manually. We use Nuget Package Manger to install these in our project.

Step 1

Right click on Project.

Step 2

Select Manage NuGet Packages.

JQuery Unobtrusive Ajax for Partial Updates in ASP.NET MVC by Nishan Aryal

Step 3

Search for Microsoft.Jquery.Unobtrusive.Ajax and Microsoft.Jquery.Unobtrusive.Validation and Install in your project.

JQuery Unobtrusive Ajax for Partial Updates in ASP.NET MVC by Nishan Aryal

Step 4

After Installation, navigate to Scripts folder of your project. You will be able to notice 4 files are added automatically as in figure

JQuery Unobtrusive Ajax for Partial Updates in ASP.NET MVC by Nishan Aryal

Now, let's create a method to load data.

Let's assume that you have already added a table called Schools and Teachers in your database. You can use either Code First method or DBFirst Method as per your need. If you want to implement CodeFirst Apprach please refer to my previous blog on Code Forst Approach in MVC 5

I prefer using Code-First Approach here. So my two modals look like,
 
School Class
 

JQuery Unobtrusive Ajax for Partial Updates in ASP.NET MVC by Nishan Aryal


Code Snippet
  1. public  class School  
  2. {  
  3.     [Key]  
  4.     public int SchoolId { getset; }  
  5.   
  6.     [Required(ErrorMessage = "Name required")]  
  7.     [Column(TypeName = "NVARCHAR")]  
  8.     [StringLength(200)]  
  9.     [DisplayName("Name")]  
  10.     public string Name { getset; }  
  11.   
  12.     [Required(ErrorMessage = "Address required")]  
  13.     [Column(TypeName = "NVARCHAR")]  
  14.     [StringLength(200)]  
  15.     public string Address { getset; }  
  16.   
  17.     [Required(ErrorMessage = "Telephone required")]  
  18.     [DisplayName("Telephone")]  
  19.     [Column(TypeName = "NVARCHAR")]  
  20.     [StringLength(200)]  
  21.     [Phone]  
  22.     public string Phone { getset; }  
  23.   
  24.     [Required(ErrorMessage = "Email required")]  
  25.     //[RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Wrong email format")]  
  26.     [EmailAddress]  
  27.     public string Email { getset; }  
  28. }   
Teacher Class

 

Code Snippet

  1. //Class: Teacher  
  2. public  class Teacher  
  3. {  
  4.     [Key]  
  5.     public int TeacherId { getset; }  
  6.   
  7.     [Required(ErrorMessage = "Name required")]  
  8.     [Column(TypeName = "NVARCHAR")]  
  9.     [StringLength(200)]  
  10.     [DisplayName("Name")]  
  11.     public string Name { getset; }  
  12.   
  13.     [Required(ErrorMessage = "Address required")]  
  14.     [Column(TypeName = "NVARCHAR")]  
  15.     [StringLength(200)]  
  16.     public string Address { getset; }  
  17.   
  18.     [Required(ErrorMessage = "Telephone required")]  
  19.     [DisplayName("Telephone")]  
  20.     [Column(TypeName = "NVARCHAR")]  
  21.     [StringLength(200)]  
  22.     [Phone]  
  23.     public string Phone { getset; }  
  24.   
  25.     [Required(ErrorMessage = "Email required")]  
  26.     //[RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Wrong email format")]  
  27.     [EmailAddress]  
  28.     public string Email { getset; }  
  29. }   
Now, let's Add Controller for Easy CRUD operations.

For now, I used Scaffolding option of MVC to generate method and Views for both Schools and Teachers table. The Controller with Methods for both Schools and Teachers looks like,

JQuery Unobtrusive Ajax for Partial Updates in ASP.NET MVC by Nishan Aryal

Let's add some data to Database using Create method for both tables.

Creating PartialViews to list Data

Let's add two methods called ListTeachers() and ListSchools() both returning PartialViews() in Home Controller as,JQuery Unobtrusive Ajax for Partial Updates in ASP.NET MVC by Nishan Aryal

Code Snippet

  1. DataContext db = new DataContext();  
  2.   
  3. //GET: AllTeachers  
  4. /// <summary>  
  5. /// List all Teachers from datasource  
  6. /// </summary>  
  7. /// <returns></returns>  
  8. public ActionResult AllTeachers()  
  9. {  
  10.     //Thread.Sleep(2000);  
  11.     return PartialView(db.Teacher.OrderBy(x => x.Name).ToList());  
  12. }  
  13.   
  14. //GET: AllSchools  
  15. /// <summary>  
  16. /// List all schools from DataSource  
  17. /// </summary>  
  18. /// <returns></returns>  
  19. public ActionResult AllSchools()  
  20. {  
  21.     //Thread.Sleep(2000);  
  22.     return PartialView(db.School.OrderBy(x => x.Name).ToList());  
  23. }  
Note

Here, in my case, I have I have used my default DataContext. If you have been working with your custom DataContext class, you need to mention your DataContext Class to retrieve and put data on Database.  
 
Now let's add Partial View for both methods

Step 1

Right click on Method and select "Add View".

JQuery Unobtrusive Ajax for Partial Updates in ASP.NET MVC by Nishan Aryal

Step 2

Select Model Class and Tick Create as Partial View as in Fig,

JQuery Unobtrusive Ajax for Partial Updates in ASP.NET MVC by Nishan Aryal

Step 3

Follow same step for ListSchools Method. You will be able to see two views inside Home Folder as

JQuery Unobtrusive Ajax for Partial Updates in ASP.NET MVC by Nishan Aryal

Adding @Ajax.ActionLink

Step 1

Let's add @Ajax.ActionLink on Index Page of Home Controller as

JQuery Unobtrusive Ajax for Partial Updates in ASP.NET MVC by Nishan Aryal

Code Snippet 

  1. @Ajax.ActionLink(    
  2.                 "List All Schools"// <-- Text to display    
  3.                 "AllSchools",// <-- Action/Method Name    
  4.                   "Home",//<!-- Controller Name    
  5.                  new AjaxOptions    
  6.                  {    
  7.                      UpdateTargetId = "UpdateContentDiv"// <-- DOM element ID to update    
  8.                      InsertionMode = InsertionMode.Replace, // <-- Replace the content of DOM element    
  9.                      HttpMethod = "GET"// <-- HTTP method    
  10.                      LoadingElementId = "divLoading"//Id of Loading GIF Image    
  11.                      OnBegin = "onAjaxBegin"//OnBegin JS Function    
  12.                      OnComplete = "onAjaxComplete" //OnComplete JS Function    
  13.                  },    
  14.                   new { @class = "btn btn-primary" } //-- Class    
  15.                  )  
Step 2

Add Loading Gif Image

Upload a loading GIF Image on Project and add following lines of codesJQuery Unobtrusive Ajax for Partial Updates in ASP.NET MVC by Nishan Aryal

Code Snippet 

  1. <div id="divLoading" class="divhide">  
  2.     @*divhide will be set as default and will be changed dynamically.*@  
  3.   
  4.     <img src="~/Loading.gif" alt="Loading Image" height="150" title="Loading Image" />  
  5. </div>  
Write CSS and Scripts to Hide and Show Loading Image on Ajax Call.

JQuery Unobtrusive Ajax for Partial Updates in ASP.NET MVC by Nishan Aryal

 

Code Snippet 
  1. @*CSS for Loading GIF Image*@  
  2. <style>  
  3.     .HideLoader {  
  4.         display: none;  
  5.     }  
  6.   
  7.     .ShowLoader {  
  8.         display: normal;  
  9.     }  
  10. </style>  
  11.   
  12. @*JS to Show and Hide Loading GIF Image*@  
  13. <script>  
  14.     function onAjaxBegin() {  
  15.         $("#divLoading").removeClass("ShowLoader").addClass("ShowLoader");  
  16.     }  
  17.   
  18.     function onAjaxComplete() {  
  19.         $("#divLoading").removeClass("ShowLoader").addClass("HideLoader");  
  20.     }  
  21. </script>  
Now Add a Div to show data after AjaxCall. Also add reference to jquery.unobtrusive-ajax.min.js as

JQuery Unobtrusive Ajax for Partial Updates in ASP.NET MVC by Nishan Aryal

Code Snippet
  1. <div id="UpdateContentDiv">  
  2.     @*Div to update content after Ajax Call*@  
  3. </div>  
  4.   
  5.   
  6. @section scripts{  
  7.     @Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js")  
  8. }  
Application Execution
 
So far we have added JQuery Unobtrusive AJAX in our project. We also learned how to implement this to load partial views. Now let's execute the application and see output.
 
Step 1

Rebuild the Solution

Step 2

Start Application in without Debugging mode (Ctrl + F5)
 JQuery Unobtrusive Ajax for Partial Updates in ASP.NET MVC by Nishan Aryal
 
Now click on List All Teachers and List All Schools and you will be able to enjoy data retrieval with our page refresh. Note: We are invoking Partial Views here using JQuery Unobtrusive Ajax. 
 
List All Teachers Button on browser will be parsed as
  1. <a class="btn btn-success" data-ajax="true" data-ajax-begin="onAjaxBegin" data-ajax-complete="onAjaxComplete" data-ajax-loading="#divLoading" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#UpdateContentDiv" href="/Home/AllTeachers?Length=4">List All Teachers</a>   
Output

 
 
Summary

So far, we have learned -
  • What is JQuery Unobtrusive Ajax.
  • How to add JQuery Unobtrusive Ajax using Nuget Package Manager in ASP.NET MC Appication.
  • How to Create PartialViews with dynamic data from DataSource. 
  • How to Implement JQuery Unobtrusive Ajax for Partial Updates in ASP.NET MVC. 
  • How to load Partial Pages using JQuery Unobstrusive AJAX. 
You may also like


Similar Articles