AJAX In ASP.NET

Introduction

These days, most of the web applications are using AJAX concepts to create better and more responsive applications. AJAX reduces the traffic between client and server and also, makes the response time faster which directly increases the performance of an application.

What is AJAX?

Asynchronous JavaScript and XML (AJAX) is a development technique used to create interactive web applications or rich internet applications. AJAX uses a number of existing technologies together, including: XHTML, CSS, JavaScript, Document Object Model, XML, XSLT, and the XMLHttpRequest object.

With AJAX, web applications can retrieve data from the server asynchronously, in the background, without reloading the entire browser page. The use of AJAX has led to an increase in interactive animation on web pages.

 
                          

Advantages
  • Reduces the traffic travels between the client and the server. 
  • No cross browser pain.
  • Better interactivity and responsiveness.
  • With AJAX, several multi purpose applications and features can be handled using a single web page(SPA).
  • API's are good because those work with HTTP method and JavaScrtipt.
Disadvantages
  • Search engines like Google would not be able to index an AJAX application. 
  • It is totally built-in JavaScript code. If any user disables JS in the browser, it won't work.
  • The server information can not be accessed within AJAX.
  • Security is less in AJAX applications as all the files are downloaded at client side.
  • The data of all requests is URL-encoded, which increases the size of the request.
For more on how AJAX works, follow here.

Using Code

We will discuss how to transfer the data through AJAX:

1. Server To Client
2. Client To Server

We use Employee as an entity to transfer the data from Client to Server and vice-versa. Employee contains two fields: ID and Name.
  1. public class Employee  
  2. {  
  3.    public int ID { getset; }  
  4.    public string Name { getset; }  

Server To Client (ASP.NET MVC)

Add following code in Controller action. Controller is Employee and action name is GetEmpList which takes list of employees as parameter.
  1. public List<Employee> GetEmpList()  
  2. {  
  3.     var empList = new List<Employee>()  
  4.     {  
  5.          new Employee { ID=1, Name="Manas"},  
  6.          new Employee { ID=2, Name="Tester"}  
  7.     };  
  8.   
  9.     return empList;  

Now, we send an AJAX request to the Server to get Employee list. Firstly, add jQuery CDN (Content Delivery Network) reference which loads jQuery library. Second, the code block to get list of employee from Server and display it.
Here, this method type is "GET", gets data in success properties as response parameter. It loops over employee list, collects employee data, and binds it as a div.
  1. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 

  2. <script type="text/javascript">

  3.     function getEmployees() {  
  4.         $.ajax({  
  5.             type: "GET",  
  6.             url: 'Employee/GetEmpList',  
  7.             data: {},  
  8.             contentType: "application/json; charset=utf-8",  
  9.             dataType: "json",  
  10.             beforeSend: function(){  
  11.                 Show(); // Show loader icon  
  12.             },  
  13.             success: function (response) {  
  14.               
  15.                 // Looping over emloyee list and display it  
  16.                 $.each(response, function (index, emp) {  
  17.                     $('#output').append('<p>Id: ' + emp.ID + '</p>' +  
  18.                                         '<p>Id: ' + emp.Name + '</p>');  
  19.                 });  
  20.             },            
  21.             complete: function(){  
  22.                 Hide(); // Hide loader icon  
  23.             },  
  24.             failure: function (jqXHR, textStatus, errorThrown) {                  
  25.                 alert("HTTP Status: " + jqXHR.status + "; Error Text: " + jqXHR.responseText); // Display error message  
  26.             }  
  27.         });  
  28.     }  
  29. </script>
Add the following code in body tag to display a loader icon when an AJAX request is sent to the Server. It hides the loader icon when AJAX completes (defined in the above AJAX code).
  1. <body>  
  2.     <div id="div_Loader" style="padding-left: 400px; top: 500px">  
  3.         <img src="Loading.gif" width="100px" height="100px" alt="loader" />  
  4.     </div>  
  5.     <div id="output">  
  6.     </div>  
  7. </body> 
Client To Server (ASP.NET MVC)
 
In the above example, we discussed how to send data from Server to Client. Next, let's see how to send data from Client to Server. Here, we will send list of Employees to the Server to save those in database.

Add the following code in Controller's action. Controller is Employee and action name is SaveEmpList which takes list of employees as parameter.
  1. public static bool SaveEmpList(List<Employee> empList)  
  2. {  
  3.     try  
  4.     {  
  5.         // Implement your logic to save EmpList in Database  
  6.     }  
  7.     catch (Exception ex)  
  8.     {  
  9.         // Log Error  
  10.         return false;  
  11.     }  
  12.       
  13.     return true;  

Here, we will send complex objects as list of employees to the Server. It creates an array and pushes JSON object to it. Then, it converts the array to JSON string using JSON.stringify() method to send the data properly.
  1. <script type="text/javascript">  
  2.     $(function () {  
  3.   
  4.         var results = new Array();  
  5.   
  6.         var emp1 = { "ID""12""Name""Manas" };  
  7.         results.push(emp1);  
  8.   
  9.         var emp2 = { "ID""2""Name""Tester" };  
  10.         results.push(emp2);       
  11.           
  12.         // Without array you can use like to construct JSON object  
  13.         // var results = { empList : [{ "ID": "1", "Name": "Manas" },   
  14.                                       { "ID""2""Name""Tester" }] };  
  15.           
  16.         var postData = { empList: results };  
  17.   
  18.         $.ajax({  
  19.             url: 'WebForm1.aspx/SaveEmpList',  
  20.             data: JSON.stringify(postData),  
  21.             type: 'POST',  
  22.             contentType: 'application/json',  
  23.             dataType: 'json',  
  24.             beforeSend: function(){  
  25.                 Show(); // Show loader icon  
  26.             },  
  27.             success: function (result) {  
  28.                 alert(result);  
  29.             },  
  30.             complete: function(){  
  31.                 Hide(); // Hide loader icon  
  32.             },  
  33.             failure: function (jqXHR, textStatus, errorThrown) {                  
  34.                 alert("Status: " + jqXHR.status + "; Error: " + jqXHR.responseText); // Display error message  
  35.             }  
  36.         });  
  37.     });  
  38.   
  39.     $(document).ready(function () {  
  40.         $("#div_Loader").hide();  
  41.     });  
  42.   
  43.     function Show() {  
  44.         $('#div_Loader').show();  
  45.     }  
  46.   
  47.     function Hide() {  
  48.         $('#div_Loader').hide();  
  49.     }  
  50.   
  51. </script> 
Above, we discussed how can we implement AJAX in jQuery using $.Ajax. MVC also facilitates two AJAX helpers to implement the same: Ajax.BeginForm, Ajax.ActionLink.
 
Ajax.BeginForm
 
There are two types of the BeginForm() extension methods:
  1. Html.BeginForm()
  2. Ajax.BeginForm()
Html.BeginForm() submits data to the Server with full page postback, means it re-loads whole page when postback occurs. Ajax.BeginForm is used to submit form data to the server without whole page postback, it sends data through AJAX concept.
 
The Ajax.BeginForm takes the following parameters:
  • actionName
  • controllerName
  • routeValues
  • ajaxOptions
  • htmlAttributes
actionName
This parameter is used to define the action name which will be executed.

controllerName
This parameter is used to define the controller name.

routeValues
It passes the object which contains the route parameters.

ajaxOptions
It passes the properties for Ajax requests which makes the request to the server asynchronously. ajaxOptions has a couple of the following properties: 
 
AllowCache
It is the boolean property which indicates whether to allow cache or not.
 
 
Confirm
It is used t
o display the confirmation box before sending request to the server.
 
HttpMethod
It sets the form submit HTTP request method like POST, GET, PUT, DELETE etc
.
 
InsertionMode
Gets or sets the mode that specifies how to insert the response into the target DOM element.
 
LoadingElementDuration
It is used to define the duration of  loading symbol in miliseconds.
 
 
LoadingElementId
It gets or sets id attribute of an HTML element that is displayed while the Ajax function is loading.
 
OnBegin
It sets JavaScript function which fires before the page is updated.
 

OnComplete
It sets JavaScript function file which fires after the complete Ajax request.
 
OnFailure
It sets JavaScript function which fires when the Ajax request failed.
 

OnSuccess
It is used to define the JavaScript function which fires after the successful Ajax request.


UpdateTargetId
It  sets the DOM element id for which part to be updated after getting result from server.
 
Url
It gets and
sets the url.
 
htmlAttributes

An
object that contains the HTML attributes to set for the element.
 
For more information about Ajax overload methods, visit here
 
Implementation
 
Step 1

Add the following User Model in Models folder.
  1. public class User  
  2. {  
  3.     [Required]  
  4.     public string Name { getset; }         
  5.   
  6.     [Required]  
  7.     public string Email { getset; }  

Step 2

Add the code for action AddUser to Controller. It receives user object as parameter. Once the model is valid, then it updates in database. Else, it returns error message.
  1. [HttpPost]  
  2. public ActionResult AddUser(User userObj)  
  3. {     
  4.     if (ModelState.IsValid)  
  5.     {  
  6.         // Add user to server  
  7.           
  8.         return Content("Success");  
  9.     }  
  10.     else  
  11.     {  
  12.         return Content("Error Occurred");  
  13.     }  

Step 3

Add the following code to define Aax.BeginForm which will send AJAX request to the respective Controller's action.
  1. @using (Ajax.BeginForm("AddUser", new AjaxOptions { OnSuccess = "OnSuccess", OnFailure = "OnFailure" }))  
  2. {  
  3.     <fieldset>  
  4.         @Html.LabelFor(m => m.Name)  
  5.         @Html.TextBoxFor(m => m.Name)  
  6.         @Html.ValidationMessageFor(m => m.Name)  
  7.           
  8.         @Html.LabelFor(m => m.Email)  
  9.         @Html.TextBoxFor(m => m.Email)  
  10.         @Html.ValidationMessageFor(m => m.Email)  
  11.           
  12.         <input type="submit" value="AddUser" />  
  13.     </fieldset>  
  14. }  
  15.   
  16. <script type="text/javascript">  
  17.     function OnSuccess(response) {  
  18.         alert(response); // Do as per requirement  
  19.     }  
  20.   
  21.     function OnFailure(response) {  
  22.         alert("Error occurred.");  
  23.     }  
  24. </script>
Ajax.ActionLink

Html.ActionLink creates a hyperlink on a View page and the user clicks it to redirects to a new URL.

Ajax.ActionLink is much like the Html.ActionLink counterpart, it also creates the hyperlink <a href="">Click Me</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 can specify the Controller's action method which is to be invoked and also specify what to perform with the response coming back from the Server action method.
 
For more about Ajax overload methods, visit here.
 
Imlementation
 
Step 1

Add the following action in
Controller which gets the list of users from datasource and returns as JSON format.
  1. [HttpGet]    
  2. public ActionResult LoadUsers()    
  3. {       
  4.     List<User> userList = List<User>(); // Load user from database    
  5.       
  6.     return Json(userList, JsonRequestBehavior.AllowGet);  
  7. }   
Step 2

The following code defines action link with required parameters like AjaxOptions, Action name, link text etc. Next, it defines a DIV where data renders and also defines JavaScript code which handles data when AJAX gets success result.
  1. @Ajax.ActionLink("Load Users""LoadUsers""User",     
  2.                 new AjaxOptions() { HttpMethod = "GET", OnSuccess = "success" });    
  3.                     
  4. <div id="result"></div>  
  5.   
  6. <script type="text/javacript>  
  7.     function success(data) {  
  8.         var jsonData = $.parseJSON(data); 

  9.         // Looping over emloyee list and display it  
  10.         $.each(jsonData, function (index, user) {  
  11.             $('#result').append('<p>Id: ' + user.Name + '</p>' +  
  12.                                 '<p>Id: ' + user.Email + '</p>');  
  13.         });  
  14.     }  
  15. </script> 
To work Ajax.BeginForm/Ajax.ActionLink functionality properly, add the following reference of jQuery library as below (if not here in folder, then download it).
  1. <script src="~/Scripts/jquery-1.10.2.js"></script>  
  2. <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>  
Also, ensure that the unobtrusive JavaScript is enabled in your web.config.
  1. <appSettings>
       <add key="ClientValidationEnabled" value="true"/>
       <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
    </appSettings>
AJAX in ASP.NET WebForms

Now, we will discuss how we can implement AJAX in ASP.NET WebForms. In the below example, we send list of employees to create in database and get all employees.

The method needs to be public, static, and add an attribute as WebMethod on top of it. Add the following code in code-behind file (*.aspx.cs) which receives list of employees and returns same.
  1. [WebMethod]  
  2. public static List<Employee> SaveEmpList(List<Employee> empList)  
  3. {  
  4.     List<Employee> tempList = new List<Employee>();  
  5.       
  6.     try  
  7.     {  
  8.         // Implement your logic to save EmpList  
  9.           
  10.         // Get it from Database  
  11.         tempList = GetItFromDB();  
  12.     }  
  13.     catch (Exception ex)  
  14.     {  
  15.         // Log Error  
  16.         return false;  
  17.     }  
  18.       
  19.     return tempList;  

Add the following code in ASPX file. It sends AJAX to WebMethod which is present in code-behind file.
  1. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 

  2. <script type="text/javascript">  
  3.     $(function () {  
  4.   
  5.         var results = new Array();  
  6.   
  7.         var emp1 = { "ID""12""Name""Manas" };  
  8.         results.push(emp1);  
  9.   
  10.         var emp2 = { "ID""2""Name""Tester" };  
  11.         results.push(emp2);       
  12.           
  13.         // Without array you can use like to construct JSON object  
  14.         // var results = { empList : [{ "ID": "1", "Name": "Manas" },   
  15.         //                            { "ID""2""Name""Tester" }] };  
  16.           
  17.         var postData = { empList: results };  
  18.   
  19.         $.ajax({  
  20.             url: 'WebForm1.aspx/SaveEmpList',  
  21.             data: JSON.stringify(postData),  
  22.             type: 'POST',  
  23.             contentType: 'application/json',  
  24.             dataType: 'json',  
  25.             beforeSend: function(){  
  26.                 Show(); // Show loader icon  
  27.             },  
  28.             success: function (response) {  
  29.                 // Looping over emloyee list and display it  
  30.                 $.each(response.d, function (index, emp) {  
  31.                     $('#output').append('<p>Id: ' + emp.ID + '</p>' +  
  32.                                         '<p>Id: ' + emp.Name + '</p>');  
  33.                 });  
  34.             },            
  35.             complete: function(){  
  36.                 Hide(); // Hide loader icon  
  37.             },  
  38.             failure: function (jqXHR, textStatus, errorThrown) {                  
  39.                 alert("Status: " + jqXHR.status + "; Error: " + jqXHR.responseText); // Display error message  
  40.             }  
  41.         });  
  42.     });  
  43.   
  44.     $(document).ready(function () {  
  45.         $("#div_Loader").hide();  
  46.     });  
  47.   
  48.     function Show() {  
  49.         $('#div_Loader').show();  
  50.     }  
  51.   
  52.     function Hide() {  
  53.         $('#div_Loader').hide();  
  54.     }  
  55.   
  56. </script> 
Exception in AJAX JSON data transfer

Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.”

Because by default MaxJsonLength property allows 102400 (100k) which is exceeding the data that your application returns. To solve the above problem, we need to increase the default value of MaxJsonLength. For that, set the MaxJsonLength property value in web.config file link:
  1. <configuration>  
  2.     <system.web.extensions>  
  3.         <scripting>  
  4.             <webServices>  
  5.                 <jsonSerialization maxJsonLength="3000000"/>  
  6.             </webServices>  
  7.         </scripting>  
  8.     </system.web.extensions>  
  9. </configuration> 
Conclusion

Thus, we discussed about AJAX and its benefits. Also, we saw how it can be implemented in ASP.NET MVC as well Webforms.

Hope this helps.

Up Next
    Ebook Download
    View all
    Learn
    View all