In this article, you will learn
- What is @Ajax.ActionLink
- How does this work?
- How to add MicrosoftMvcAjax.js & MicrosoftAjax.js in MVC Project.
- Add a loading image while loading data.
- 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
- <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.
Step 3
Search for Microsoft.Jquery.Unobtrusive.Ajax and Microsoft.Jquery.Unobtrusive.Validation and Install in your project.
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
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
Code Snippet
- public class School
- {
- [Key]
- public int SchoolId { get; set; }
-
- [Required(ErrorMessage = "Name required")]
- [Column(TypeName = "NVARCHAR")]
- [StringLength(200)]
- [DisplayName("Name")]
- public string Name { get; set; }
-
- [Required(ErrorMessage = "Address required")]
- [Column(TypeName = "NVARCHAR")]
- [StringLength(200)]
- public string Address { get; set; }
-
- [Required(ErrorMessage = "Telephone required")]
- [DisplayName("Telephone")]
- [Column(TypeName = "NVARCHAR")]
- [StringLength(200)]
- [Phone]
- public string Phone { get; set; }
-
- [Required(ErrorMessage = "Email required")]
-
- [EmailAddress]
- public string Email { get; set; }
- }
Teacher Class
Code Snippet
-
- public class Teacher
- {
- [Key]
- public int TeacherId { get; set; }
-
- [Required(ErrorMessage = "Name required")]
- [Column(TypeName = "NVARCHAR")]
- [StringLength(200)]
- [DisplayName("Name")]
- public string Name { get; set; }
-
- [Required(ErrorMessage = "Address required")]
- [Column(TypeName = "NVARCHAR")]
- [StringLength(200)]
- public string Address { get; set; }
-
- [Required(ErrorMessage = "Telephone required")]
- [DisplayName("Telephone")]
- [Column(TypeName = "NVARCHAR")]
- [StringLength(200)]
- [Phone]
- public string Phone { get; set; }
-
- [Required(ErrorMessage = "Email required")]
-
- [EmailAddress]
- public string Email { get; set; }
- }
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,
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,
Code Snippet
- DataContext db = new DataContext();
-
-
-
-
-
-
- public ActionResult AllTeachers()
- {
-
- return PartialView(db.Teacher.OrderBy(x => x.Name).ToList());
- }
-
-
-
-
-
-
- public ActionResult AllSchools()
- {
-
- return PartialView(db.School.OrderBy(x => x.Name).ToList());
- }
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".
Step 2
Select Model Class and Tick Create as Partial View as in Fig,
Step 3
Follow same step for ListSchools Method. You will be able to see two views inside Home Folder as
Adding @Ajax.ActionLink
Step 1
Let's add @Ajax.ActionLink on Index Page of Home Controller as
Code Snippet
- @Ajax.ActionLink(
- "List All Schools",
- "AllSchools",
- "Home",
- new AjaxOptions
- {
- UpdateTargetId = "UpdateContentDiv",
- InsertionMode = InsertionMode.Replace,
- HttpMethod = "GET",
- LoadingElementId = "divLoading",
- OnBegin = "onAjaxBegin",
- OnComplete = "onAjaxComplete"
- },
- new { @class = "btn btn-primary" }
- )
Step 2
Add Loading Gif Image
Upload a loading GIF Image on Project and add following lines of codes
Code Snippet
- <div id="divLoading" class="divhide">
- @*divhide will be set as default and will be changed dynamically.*@
-
- <img src="~/Loading.gif" alt="Loading Image" height="150" title="Loading Image" />
- </div>
Write CSS and Scripts to Hide and Show Loading Image on Ajax Call.
Code Snippet
- @*CSS for Loading GIF Image*@
- <style>
- .HideLoader {
- display: none;
- }
-
- .ShowLoader {
- display: normal;
- }
- </style>
-
- @*JS to Show and Hide Loading GIF Image*@
- <script>
- function onAjaxBegin() {
- $("#divLoading").removeClass("ShowLoader").addClass("ShowLoader");
- }
-
- function onAjaxComplete() {
- $("#divLoading").removeClass("ShowLoader").addClass("HideLoader");
- }
- </script>
Now Add a Div to show data after AjaxCall. Also add reference to jquery.unobtrusive-ajax.min.js as
Code Snippet
- <div id="UpdateContentDiv">
- @*Div to update content after Ajax Call*@
- </div>
-
-
- @section scripts{
- @Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js")
- }
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)
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
- <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