Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery $.ajax() call to webmethod

Tags:

json

jquery

ajax

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

like image 781
Daniel Svensson Avatar asked Mar 28 '26 20:03

Daniel Svensson


1 Answers

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.

like image 103
benpage Avatar answered Mar 31 '26 11:03

benpage



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!