Wednesday, May 22, 2013

Basic Ajax request

If we have to create an application that uses Ajax to dynamically get and manage data in an MVC 3 project we have to create a controller action that will deal with the Ajax request and an Ajax call at the user interface level which will call the action and manage the output. To implement this we first need to write down the following controller action.

Controller: 

public class HomeController : Controller
{
                public ActionResult TestAjax(string input)
{
List<string> output = new List<string>(){"a","b","c"};
output.Add(input);
       return Json(output, JsonRequestBehavior.AllowGet);
}
}

This is just like a normal controller action which takes input in the form of a string (called input), appends it to the list ‘output’ and returns the result as a JSon object (instead of a view which typical controllers return).
After this we need to write the following jQuery code to call this action and manage its result.
 

jQuery:

$(document).ready(function () {
   
    $(".link").click(function () {       
        $.ajax({
            type: "GET",
            url: "/Home/TestAjax",
            data: {input: "d"},
            dataType: "json",
            success: function(data) {
                alert(data);
            }
        });

    });
});

In the code above we have a javascript function that is executed whenever we click the control with class "link". This function creates a GET request to the url “…/Home/TestAjax” (which you might have noticed are the names of the controller and action we created above) and passes "d" to the actions’ input parameter “input”. The controller then creates a list containing "a,b,c" and appends the input parameter "d" to it and returns the final string i.e "a,b,c,d" as a JSon object. Once the controller successfully returns this output, the javascript function in the “success” parameter is executed, which gets the output provided by the action in its own variable “data” and shows it as an alert as shown below:




And that is it, a simple Ajax call made.

P.S: You might have noticed that this code is added to the document.ready function. This is done because if we don’t place it there we would have to specifically add it to the control’s onclick event.

No comments:

Post a Comment