This is a mirror of official site: http://jasper-net.blogspot.com/

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

| Wednesday, July 28, 2010
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);
}

Read more: DZone

Posted via email from .NET Info

0 comments: