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).
  • APIs are good because they work with the 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.

public class Employee  
{  
    public int ID { get; set; }  
    public string Name { get; set; }  
}  

Server To Client (ASP.NET MVC)

Add the following code in the Controller action. The controller is Employee and the action name is GetEmpList which takes a list of employees as a parameter.

public List<Employee> GetEmpList()
{
    var empList = new List<Employee>()
    {
        new Employee { ID = 1, Name = "Manas" },
        new Employee { ID = 2, Name = "Tester" }
    };
    return empList;
}

Now, we send an AJAX request to the Server to get an Employee list. Firstly, add a jQuery CDN (Content Delivery Network) reference which loads the jQuery library. Second, the code block to get a list of employees from the Server and display it.

Here, this method type is "GET", which gets data in success properties as a response parameter. It loops over the employee list, collects employee data, and binds it as a div.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    function getEmployees() {  
        $.ajax({
            type: "GET",
            url: 'Employee/GetEmpList',
            data: {},
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function(){
                Show(); // Show loader icon
            },
            success: function (response) {
                // Looping over employee list and display it
                $.each(response, function (index, emp) {
                    $('#output').append('<p>Id: ' + emp.ID + '</p>' +
                                        '<p>Id: ' + emp.Name + '</p>');
                });
            },            
            complete: function(){
                Hide(); // Hide loader icon
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert("HTTP Status: " + jqXHR.status + "; Error Text: " + jqXHR.responseText); // Display error message
            }
        });
    }
</script>

Add the following code in the 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).

<body>
    <div id="div_Loader" style="padding-left: 400px; top: 500px">
        <img src="Loading.gif" width="100px" height="100px" alt="loader" />
    </div>
    <div id="output">
    </div>
</body>

Client To Server (ASP.NET MVC)

In the above example, we discussed how to send data from the Server to the Client. Next, let's see how to send data from Client to Server. Here, we will send a list of Employees to the Server to save those in the database.

Add the following code in the Controller's action. The controller is Employee and the action name is SaveEmpList which takes a list of employees as a parameter.

public static bool SaveEmpList(List<Employee> empList)
{
    try
    {
        // Implement your logic to save EmpList in Database
        // For example:
        // dbContext.Employees.AddRange(empList);
        // dbContext.SaveChanges();
    }
    catch (Exception ex)
    {
        // Log Error
        return false;
    }  
    return true;
}

Here, we will send complex objects as a 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 the JSON.stringify() method to send the data properly.

<script type="text/javascript">
    $(function () {
        var results = new Array();
        var emp1 = { "ID": "12", "Name": "Manas" };
        results.push(emp1);
        var emp2 = { "ID": "2", "Name": "Tester" };
        results.push(emp2);
        // Without array you can use like to construct JSON object
        // var results = { empList : [{ "ID": "1", "Name": "Manas" },
        // { "ID": "2", "Name": "Tester" }] };
        var postData = { empList: results };
        $.ajax({
            url: 'WebForm1.aspx/SaveEmpList',
            data: JSON.stringify(postData),
            type: 'POST',
            contentType: 'application/json',
            dataType: 'json',
            beforeSend: function(){
                Show(); // Show loader icon
            },
            success: function (result) {
                alert(result);
            },
            complete: function(){
                Hide(); // Hide loader icon
            },
            failure: function (jqXHR, textStatus, errorThrown) {
                alert("Status: " + jqXHR.status + "; Error: " + jqXHR.responseText); // Display error message
            }
        });
    });
    $(document).ready(function () {
        $("#div_Loader").hide();
    });
    function Show() {
        $('#div_Loader').show();
    }
    function Hide() {
        $('#div_Loader').hide();
    }
</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.

Html.BeginForm()
Ajax.BeginForm()

Html.BeginForm() submits data to the Server with full-page postback, which means it re-loads the whole page when a 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.

Route values

It passes the object that 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.

  1. AllowCache: It is the boolean property which indicates whether to allow cache or not.
  2. Confirm: It is used to display the confirmation box before sending a request to the server.
  3. HttpMethod: It sets the form submit HTTP request method like POST, GET, PUT, DELETE, etc.
  4. InsertionMode: Gets or sets the mode that specifies how to insert the response into the target DOM element.
  5. LoadingElementDuration: It is used to define the duration of the loading symbol in milliseconds.
  6. LoadingElementId: It gets or sets id attribute of an HTML element that is displayed while the Ajax function is loading.
  7. OnBegin: It sets the JavaScript function which fires before the page is updated.
  8. OnComplete: It sets the JavaScript function file which fires after the complete Ajax request.
  9. OnFailure: It sets a JavaScript function that fires when the Ajax request fails.
  10. OnSuccess: It is used to define the JavaScript function that fires after the successful Ajax request.
  11. UpdateTargetId: It sets the DOM element id for which part to be updated after getting a result from the server.
  12. Url: It gets and sets the URL.

HTML attributes

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 the Models folder.

public class User
{
    [Required]
    public string Name { get; set; }
    [Required]
    public string Email { get; set; }
}

Step 2. Add the code for action AddUser to Controller. It receives the user object as a parameter. Once the model is valid, then it updates in the database. Else, it returns an error message.

[HttpPost]
public ActionResult AddUser(User userObj)
{
    if (ModelState.IsValid)
    {
        // Add user to server

        return Content("Success");
    }
    else
    {
        return Content("Error Occurred");
    }
}

Step 3. Add the following code to define Aax.BeginForm which will send AJAX requests to the respective Controller's action.

@using (Ajax.BeginForm("AddUser", new AjaxOptions { OnSuccess = "OnSuccess", OnFailure = "OnFailure" }))
{
    <fieldset>
        @Html.LabelFor(m => m.Name)
        @Html.TextBoxFor(m => m.Name)
        @Html.ValidationMessageFor(m => m.Name)   
        @Html.LabelFor(m => m.Email)
        @Html.TextBoxFor(m => m.Email)
        @Html.ValidationMessageFor(m => m.Email)      
        <input type="submit" value="AddUser" />
    </fieldset>
}
<script type="text/javascript">
    function OnSuccess(response) {
        alert(response); // Do as per requirement
    }
    
    function OnFailure(response) {
        alert("Error occurred.");
    }
</script>

Ajax.ActionLink

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

Ajax.ActionLink is much like 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.

Implementation

Step 1. Add the following action in Controller which gets the list of users from datasource and returns as JSON format.

[HttpGet]
public ActionResult LoadUsers()
{
    List<User> userList = List<User>(); // Load user from database   
    return Json(userList, JsonRequestBehavior.AllowGet);
}

Step 2. The following code defines action links 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 a successful result.

@Ajax.ActionLink("Load Users", "LoadUsers", "User", 
                new AjaxOptions() { HttpMethod = "GET", OnSuccess = "success" });
                
<div id="result"></div> 
<script type="text/javascript"> 
    function success(data) {
        var jsonData = $.parseJSON(data);

        // Looping over employee list and display it
        $.each(jsonData, function (index, user) {
            $('#result').append('<p>Id: ' + user.Name + '</p>' +
                                '<p>Id: ' + user.Email + '</p>');
        });
    } 
</script>

To work Ajax.BeginForm/Ajax.ActionLink functionality properly, add the following reference of jQuery library as below (if not here in a folder, then download it).

<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>

Also, ensure that unobtrusive JavaScript is enabled on your web. config.

<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 a list of employees to create in the database and get all employees.

The method needs to be public, and static, and add an attribute as WebMethod on top of it. Add the following code in the code-behind file (*.aspx.cs) which receives a list of employees and returns the same.

[WebMethod]
public static List<Employee> SaveEmpList(List<Employee> empList)
{
    List<Employee> tempList = new List<Employee>();
    try
    {
        // Implement your logic to save EmpList
        // Get it from Database
        tempList = GetItFromDB();
    }
    catch (Exception ex)
    {
        // Log Error
        return false;
    }
    return tempList;
}

Add the following code in the ASPX file. It sends AJAX to WebMethod which is present in the code-behind file.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        var results = new Array();
        var emp1 = { "ID": "12", "Name": "Manas" };
        results.push(emp1);
        var emp2 = { "ID": "2", "Name": "Tester" };
        results.push(emp2);
        // Without array you can use like to construct JSON object
        // var results = { empList : [{ "ID": "1", "Name": "Manas" },
        //                           { "ID": "2", "Name": "Tester" }] };
        var postData = { empList: results };
        $.ajax({
            url: 'WebForm1.aspx/SaveEmpList',
            data: JSON.stringify(postData),
            type: 'POST',
            contentType: 'application/json',
            dataType: 'json',
            beforeSend: function(){
                Show(); // Show loader icon
            },
            success: function (response) {
                // Looping over emloyee list and display it
                $.each(response.d, function (index, emp) {
                    $('#output').append('<p>Id: ' + emp.ID + '</p>' +
                                        '<p>Id: ' + emp.Name + '</p>');
                });
            },            
            complete: function(){
                Hide(); // Hide loader icon
            },
            failure: function (jqXHR, textStatus, errorThrown) {
                alert("Status: " + jqXHR.status + "; Error: " + jqXHR.responseText); // Display error message
            }
        });
    });
    $(document).ready(function () {
        $("#div_Loader").hide();
    });
    function Show() {
        $('#div_Loader').show();
    }
    function Hide() {
        $('#div_Loader').hide();
    }
</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.

<configuration>
    <system.web.extensions>
        <scripting>
            <webServices>
                <jsonSerialization maxJsonLength="3000000"/>
            </webServices>
        </scripting>
    </system.web.extensions>
</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.


Similar Articles