0

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 a variable number of properties-filters. On the server-side, I get an object array where the first item is a string, containing the [Object object] literal.

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

Thank you very much.

3 Answers 3

3

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
 }
});
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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) {

 }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.