How to make AJAX-requests to ASP.NET MVC application using jQuery

I decided to write over long time one posting that is directed to beginners who start with jQuery and AJAX. One of the first things to study is how to make requests to server and how to retrieve objects. In this posting I will show you how to use jQuery to retrieve JSON data from ASP.NET MVC application and how to debug it.

Making AJAX-requests to server

This was one of first things I needed when I started with jQuery. If you are working on ASP.NET MVC there are some tricks but I tell about these later. Now let’s see how to make AJAX-request to server.


var url = '/contacts/ListPartiesByNameStart?nameStart=A';
$.ajax({ url: url, success: DataRetrieved, type: 'POST', dataType: 'json' });

Should be simple but let me still explain a little bit.

  • url – this is the URL where request is sent. In my case there is controller called contacts and it has action calles ListPartiesByNameStart(). This action method takes  parameter nameStart (first letter of person or company).
  • success – this is the JavaScript function that handles retrieved data. You can write there also anonymous function but I suggest you to use functions with names because otherwise your code may get messy when functions grow.
  • type – this is the type of request. It is either GET or POST. I suggest you to use POST because GET requests in JSON format are forbidden by ASP.NET MVC by default (I will show you later how to turn on GET requests to JSON returning actions).
  • dataType – this is the data format that is expected to be returned by server. If you don’t assign it to value then returned result is handled as string. If you set it to json then jQuery constructs you JavaScript object tree that corresponds to JSON retrieved from server.

If you are using POST requests then I suggest you to use parameter called data that is serialized as POST body. You can find more information about parameters from jQuery ajax() method documentation. And here you can find jQuery API documentation.

Here is the example of DataRetrieved function where I expected that server returned person object in JSON format.


function DataRetrieved(data) {
// Do something with data
alert(data.FirstName + ' ' + data.LastName);
}

The data that is given to this method is exactly the same thing you send from server. Now let’s see how to make your web application to output JSON.

Returning JSON from ASP.NET MVC actions

ASP.NET MVC is able to create JSON results for yourself automatically. You don’t have to write your own object transformers and anything else. Just use what ASP.NET MVC offers. Here is the example action that returns some data in JSON format.


public JsonResult ListCompanyNames(int id)
{
    var party = _partyRepository.GetCompanyById(id);
    var names = from n in party.Names
                select new 
                {
                    nameId = n.Id.ToString(),
                    name = n.Name.ToString(),
                    validTo = n.ValidTo.ToShortDateString(),
                    userdata = ""
                };
    var rows = names.ToArray();
    var data = new JqGridData
                {
                    total = rows.Count(),
                    page = 1,
                    records = rows.Count(),
                    rows = rows
                };
    return Json(data,JsonRequestBehavior.AllowGet);
}

I ask some data and form objects that I want to send as response to browser. All I have to do is to use Json() method of controller. In this case I allow also GET requests. If I omit second parameter then GET requests to this action are not allowed

How to debug

As a last thing let’s see how to debug AJAX-requests. One option is to use AllowGet as in previous code sample but I don’t suggest it. It makes direct data requests to JSON data too easy for users with browsers. Although you win practically nothing in security you still make life harder for not so educated bad guys.

My favorite choice is Firebug extension for Firefox. Firebug monitors requests and responses made by browser and gives you very good overview about data that is moving between browser and server. Firebug is also able to illustrate JSON data like shown on following screenshot fragment.

Firebug showing JSON objects retrieved from web server

Here you can see array of JSON objects that have Id and DisplayName properties.

Conclusion

Writing AJAX-based applications using ASP.NET MVC framework and jQuery is easy. You have two powerful tools that let you do more spending less time. ASP.NET MVC is very lightweight framework but in the same time extremely effective tool to build web applications. Same goes for jQuery that is client-side technology. Mixing two of them together it is fun to be web developer.

1 Comment

Comments have been disabled for this content.