tags:

views:

272

answers:

2

Hi,

I have never before used the $.ajax() and if you see any mistypes let me know ;)

Im using jQuery $.ajax() to call a webmethod with JSON.

The simple definition of the webmethod should look something like this:

[WebMethod]
public static bool MyMethod(string a, string b, string c) {
   ...
}

The value for the data parameter in $.ajax() is:

myData => "'a':'val_a', 'b':'val_b','c':'val_c'"

Here is my ajax call:

    $.ajax({
            type: "POST",
            url: "AspDotNetPage.aspx/MyMethod",
            data: "{"+myData+"}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
               alert(msg);                
            }
          });

Now the tricky part comes. I need to add an extra parameter to my webmethod. I must send to my webmethod all checkboxes inside a certain div, their names and if they are checked. I have Jquery code to select these values. Here is where i see in normal code-behind programming an additional parameter would be like

[WebMethod]
public static bool MyMethod(string a, string b, string c, Dictionary<string,bool> dict) {
       ...
}

that holds my checkbox text-value and if it's checked.

I haven't the foggiest idea how JSON actually works, all i know is that i have to make this work soon.

Probably some sort of multi dimensional javascripts arrays must be used. If you have any ideas on the best approach for this question i would be glad!

/Daniel Svensson, Sweden

A: 

Assuming this is about ASP.NET, seems the same as http://stackoverflow.com/questions/1527422/send-json-to-webmethod

Nickolay
+1  A: 

if you make your bools nullable, you can just use the .serialize() method on all your values, and the checkboxes that aren't in the posted data will simply be ignored by the method:

[WebMethod]
public static bool MyMethod(string a, string b, string c, bool? chkbox1, bool? chkbox2....) {
       ...
}

you would need to add a bool? parameter for all your possible checkboxes on the page. that's the best way to provide a good method for testing etc. however if you really wanted to you could add another object to your data, for instance

data: { 'a':'val_a', 'b':'val_b','c':'val_c', 'dict': { 'chk1', 'chk2', 'chk3' } }

where chk1, chk2, chk3 is an array you've built of checked checkboxes, and your dict param would simply become a string array.

benpage