views:

314

answers:

3

I would like to pass a nested JavaScript object to my ASP.NET MVC Action Method. Here is the code(simplified):

$.getJSON('some/url',
               {

                  index: pageIndex,
                  pageSize: pageSize,
                  filter:{one:'one',two:'two',three:'three'}
               },someCallBack(msg)
         );

I'm using jQuery and implemented my plugin which lazily fetches paginated data from the server. It works all charm but now I need to pass a JavaScript 'Filter' object with variable number of properties-filters. On the server side I get an object array where first item is a string, containing the '[Object object]' literal.

Obviously, my nested object (filter) is not being expanded and transformed into object(hash) on the server side. Is this possible at all?? I don't wan't to hard code my filters, since the plugin is meant to be unversally applied.

Thank you very much.

+1  A: 

JSON would be perfect for this. Basically, you'll want to convert your object to it's JSON representation and then send that across the wire. Once it's available on the server, you can process it however you like.

Crockford has a great article on what JSON is, how to understand the notation, and he provides a tool to convert your objects to JSON notation.

Tom
+1  A: 

You can use the following js lib json2 library, you can then use the stringify method to ensure your json is in the correct format for the service.

var data0 = {one:'one',two:'two',three:'three'}

var json = JSON2.stringify(data0 ); 

$.ajax({
 type: "POST",
 url: someServiceUrl,
 data: json,
 contentType: "application/json; charset=utf-8",
 dataType: "json",
 success: function(msg) {

 }
});
redsquare
+3  A: 

You can use System.Web.Script.Serialization.JavaScriptSerializer to send/receive JSON serialized data:

JavaScriptSerializer js = new JavaScriptSerializer();
Filter f = js.Deserialize<Filter>(json_str);

More details here. To encode the JSON data to send to the server, use a JSON serialization library for JavaScript like json2.js. Then send the query like this:

var filter = {field1: 'value1', field2: 'value2'}

$.ajax({
 type: "POST",
 url: '/server/path',
 data: { filter: JSON2.stringify(filter) },
 dataType: "json",
 success: function(data) {
   // do something
 }
});
Augustus