ASP.NET MVC AJAX Helper

I hope you have basic knowledge of the HTML helper method available in ASP.NET MVC . If you have no idea about the HTML helper method, I recommend you to go through the HTML helper before proceeding through this article.

You know that MVC framework supports AJAX features. Like the HTML helper method ASP.NET MVC has a AJAX helper. Both the HTML helper method and AJAX helper method are used to create the HTML markup. These methods generate the form tag and anchor tag that points to the controller action method. But the main difference is that the HTML helper calls the controller action method synchronously (i.e entire page refresh) while the AJAX helper calls asynchronously (I.e just refresh the portion of page that display updated info).

To get AJAX helper support in your project, you must have jquery.unobstrusive.ajax.js script library in your project.You can get this library via NuGet package manager console or NuGet package dialog.

There are two ways to install jquery.unobstrusive.ajax.js library into your project. 

Option 1: Install via NuGet package manager console

Open Visual Studio, Tools, NuGet Package Manager, then click Package Manager Console and perform the following command on NuGet console.

Install-Package jquery.unobstrusive.ajax.js

 

Option 2: Install via NuGet package dialog.

Right click on project name in solution explorer and go to Manage NuGet Packages option.

Now search for the following term Microsoft.jQuery.Unobtrusive.Ajax. Click on install button.

 

When you perform these commands visual studio will add two java script file in your project Scripts folder.

 

After adding this script AJAX helper intelligence is now available in a view and layout page.

  

Now it’s time to add script reference in a view or layout page.

NOTE
if your application is making too many AJAX requests throughout the project it is better to add a reference in a layout page. In the code sample I have added this script reference in _Layout page just below the jquery.min.js script reference.
  1. <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script> 
We have seen that both HTML helper and AJAX helper method generate the anchor tag, now the question is where to use the @HTML.ActionLink and @AJAX.ActionLink.

For that consider the following situation.

Whenthe  user clicks on the link and you want to redirect user to another different page in that situation you have to use @HTML.ActionLink.

When the user clicks on the link and you don’t want to redirect to different page, but you want them to stay on the same page and display some information or details without Post Back, at that time it’s better to use @AJAX.ActionLink.

@AJAX.ActionLink has 12 different overloads; here I have explained the most important one that is mostly used.

In the sample code I have used ASP.NET MVC5 applications using the Entity Framework 6 and Visual Studio 2015. For more information about how to work with Entity Framework Getting Started with Entity Framework 6 using MVC 5

@AJAX.ActionLink Example

1. Create AJAX action link,
 
/Views/Home/Index.cshtml
  1. @Ajax.ActionLink("View  All Student Info""AllStudent""Home"new AjaxOptions  
  2.    {  
  3.        UpdateTargetId = "divAllStudent",  
  4.        OnBegin = "fnOnBegin",  
  5.        InsertionMode = InsertionMode.Replace,  
  6.        HttpMethod = "GET",  
  7.        LoadingElementId = "imgloader",  
  8.        OnSuccess= "fnSuccess",  
  9.        Confirm="Do you want to get all student info ?????"  
  10.    }, new { @class = "btn btn-default" })   

/Controllers/HomeController.cs

2. Create action method.that will call on action click event.
  1.         [HttpGet]  
  2.         public PartialViewResult AllStudent()  
  3.         {  
  4.             using (TempEntities db = new TempEntities())  
  5.             {  
  6.                 var objAllStudent = db.StudentInfoes.ToList();  
  7.                 return PartialView("AllStudent", objAllStudent);  
  8.             }  
  9.         } 

Views/Home/AllStudent.cshtml

3. creating a partial view that will return all student info.
  1. @model IEnumerable<StudentInfo>    
  2. <table class="table">    
  3.     <tr>    
  4.         <th>@Html.DisplayNameFor(model => model.FirstName)</th>    
  5.         <th>@Html.DisplayNameFor(model => model.LastName)</th>    
  6.         <th> @Html.DisplayNameFor(model => model.MobileNo)</th>    
  7.         <th>@Html.DisplayNameFor(model => model.Address)</th>    
  8.     </tr>    
  9.     
  10. @foreach (var item in Model) {    
  11.     <tr>    
  12.         <td> @Html.DisplayFor(modelItem => item.FirstName)</td>    
  13.         <td>@Html.DisplayFor(modelItem => item.LastName)</td>    
  14.         <td>@Html.DisplayFor(modelItem => item.MobileNo)</td>    
  15.         <td> @Html.DisplayFor(modelItem => item.Address)</td>    
  16.     </tr>    
  17. }    
  18. </table>   

In @Ajax.ActionLink,First parameter is the link text that will be displayed on the User Interface. Second parameter is an action method name that you want to call asynchronously. Third parameter is name of controller. Now the most important parameter is AjaxOptions. The following different options are available in AjaxOptions class.

  1. Allowcache

  2. Confirm

  3. HttpMethod

  4. InsertionMode

  5. LoadingElementDuration

  6. LoadingElementId

  7. OnBegin

  8. OnComplete

  9. OnFailure

  10. OnSuccess

  11. UpdateTargetId

  12. Url

1. AllowCache:

By Default it is false, it specifies whether you want to cache the page requested by the browser or not by specifying its value as true or false. 

2. Confirm:

This is the parameter that executes first if you have specified. This property is used to specify what message text will be displayed in a confirmation window before request is submitted.i.e when you click on “View All Student Info” link. It will display confirmation window before sending AJAX request.

  

3. HttpMethod: Specifies the HTTP request method. that is either GET or POST. by default it is POST.

4. InsertionMode: 

This enumeration property specifies how to insert the response coming back from the action method into the target DOM element (here DOM element is <div> tag UpdateTargetId = "divAllStudent"). In the above example I have specified the InsertionMode as a Replace mode so whatsever the response coming back will be inserted into

  1. <div id="divAllStudent"></div>.  

InsertionMode enumeration contain four different value.

  1. InsertAfter
  2. InsertBefore
  3. Replace
  4. ReplaceWith    

Default InsertionMode value is “Replace”.

5. LoadingElementDuration: Here you can specify the value in milliseconds that controls the duration ofthe animation loading element.

6. LoadingElementId: HTML element that will be displayed when AJAX call is in-progress.

Generally we used this property to display the loader element.i.e.

  1. <div id="imgloader" style="display:none;position:absolute;top:50%;left:50%;padding:2px;">    
  2.     <img src="~/Content/loader.gif" />    
  3. </div>    

7. OnBegin:

This property specifies the name of the java script function that is called just before Ajax starts. so here you can perform some validation or other operation that is required before Ajax starts. i.e OnBegin = "fnOnBegin",

  1. <script type="text/javascript">    
  2.     function fnOnBegin() {    
  3.         if ($("#txtSearchValue").trim() == null)    
  4.         {    
  5.             return false;    
  6.         }    
  7.         return true;    
  8.     }    
  9. </script> 

8. OnComplete: name of the java script function that will be called when response data has been represented by the AJAX call.

9. OnFailure: name of the java script function to call when AJAX request returns error.

10. OnSuccess:

name of the java script function to call after the AJAX request returns successfully. You can also check the AJAX call return status in browser,i.e press Ctrl+Shift+i and goto Network tab.

  1. <script type="text/javascript">  
  2.     function fnSuccess() {  
  3.         alert("Booo..Success..");  
  4.     }  
  5. </script> 
 

11. UpdateTargetId:

This property is used to specify the ID of HTML element that is updated by using the response; i.e, here I have specified the div element with the id “divAllStudent”.

  1. <div id="divAllStudent" class="col-md-12">  
  2. </div>    

12. URL: specify the URL to make call.i.e External URL link.

@AJAX.BeginForm Example 

1. create AJAX form
 
/Views/Home/Index.cshtml
  1. @using (Ajax.BeginForm("SearchStudent""Home"new AjaxOptions  
  2.        {  
  3.            InsertionMode = InsertionMode.Replace,  
  4.            HttpMethod = "GET",  
  5.            LoadingElementId = "imgloader",  
  6.            OnFailure = "fnError",  
  7.            OnBegin = "fnOnBegin",  
  8.            UpdateTargetId = "divSearchStudent",  
  9.        }))  
  10.        {  
  11.            <div class="form-horizontal">  
  12.                <div class="form-group">  
  13.                    Student Name:  
  14.                    <input type="text" name="SearchTerm" placeholder="Keyword" class="form-control" />  
  15.                </div>  
  16.                <div class="form-group">  
  17.                    <input type="submit" value="Search" class="btn btn-default" />  
  18.                </div>  
  19.            </div>  
  20.        }  
  21.    <div id="divSearchStudent"></div> 
2. Create action method that will called asynchronously when form is submited.

/Controllers/HomeController.cs
  1. [HttpGet]  
  2.        public ActionResult SearchStudent(string SearchTerm)  
  3.        {  
  4.            if (SearchTerm != null)  
  5.            {  
  6.                using (TempEntities db = new TempEntities())  
  7.                {  
  8.                    var objSearchStudent = db.StudentInfoes.Where(x => x.FirstName.Contains(SearchTerm) ||  
  9.                                              x.LastName.Contains(SearchTerm) ||  
  10.                                              x.MobileNo.Contains(SearchTerm) ||  
  11.                                              x.Address.Contains(SearchTerm)).AsEnumerable().Select(x => new StudentInfo  
  12.                                              {  
  13.                                                  Address = x.Address,  
  14.                                                  FirstName = x.FirstName,  
  15.                                                  LastName = x.LastName,  
  16.                                                  MobileNo = x.MobileNo  
  17.                                              });  
  18.                    return PartialView("AllStudent", objSearchStudent.ToList());  
  19.                }  
  20.            }  
  21.            return View();  
  22.        }  

When you click on the search button, an asynchronous request is sent to the “SearchStudent” action method inside the home controller and all the form data is submitted to action method. This action method returns the partial view content that will be placed inside the “divSearchStudent” DOM element.

Read more articles on AJAX,


Similar Articles