简体   繁体   中英

How to pass a nested JavaScript object to ASP.NET MVC Action Method?

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.

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
 }
});

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.

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

 }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM