Passing Multiple Json Objects as data using jQuery's $.ajax()

后端 未结 5 1329
醉话见心
醉话见心 2020-12-16 23:19

I am POSTing data to an MVC controller and I\'m attempting to maintain state as well for optimistic concurrency. I\'m currently posting back a JSON request, but would be op

相关标签:
5条回答
  • 2020-12-16 23:57

    i think you can do something like this:

    var data = {};
    var object1 = {};
    var object2 = {};
    
    data.object1 = object1;<br/>
    data.object2 = object2;
    
    // serializer
    
    JSON2.stringify(data);
    
    0 讨论(0)
  • 2020-12-17 00:03

    This is an answer after a really long time, but may be helpful to you for any future reference.

    I suggest you read this stackoverflow answer that is directly addressing your problem.

    0 讨论(0)
  • 2020-12-17 00:13

    You can do this in a simple way in asp.net ,if u just want to send multiple data to webmethod

    data: '{userName: "' + $("#<%=txtUserName.ClientID%>")[0].value + '",userName1: "' + $("#<%=TextBox1.ClientID%>")[0].value + '" }',
    
    0 讨论(0)
  • 2020-12-17 00:18

    As far as I know, there is no way to send back two completely different JSON objects that aren't children of a single parent JSON object and have jQuery decode it for you using the .ajax() method. You could, I suppose, reply with two JSON objects as strings and then use an external JSON library to evaluate the strings into a Javascript Object.

    Does that answer your question?

    Ooops: You're asking about posting two distinct JSON objects to your controller from jquery..., right? My bad... Yeah, you can do that... Just change this line:

    data: $.toJSON(data),
    

    to:

    data: { json_1:$.toJSON(data_1), json_2:$.toJSON(data_2) },
    

    Sorry about the mix-up.

    0 讨论(0)
  • 2020-12-17 00:21

    If I understand you correctly, functional speaking, you want to send

    object 1,
    object 2
    

    which is equivalent to sending

    [
        object 1,
        object 2
    ]
    

    The only difference is that the array in the former case is implicit, while in latter it's explicit. It's still there either way, but if you want to send multiple objects in JSON you need to use the explicit approach.

    So wrapping the two data objects in an array is really the ideal choice, but if your sever code isn't going to support that you'll need an alternative. The only possible method I can see to do this would be to put both data objects inside another object, like this:

    var data = {};
    data[0] = data1;
    data[1] = data2;
    

    And then you send data along through the AJAX call.

    I would go so far as to say that the problem isn't your approach, but rather the JSON handling on the receiving end.

    0 讨论(0)
提交回复
热议问题