开发者

calling a PageMethod with params object[] args from jQuery

开发者 https://www.devze.com 2023-03-10 15:42 出处:网络
Is there a way to call a Page Method in jQuery when the page method has a \"params\" argument type (in C#)?

Is there a way to call a Page Method in jQuery when the page method has a "params" argument type (in C#)? I can call Page Methods all day long using jQuery if I specify the arguments one at a time, but if I put them as "params object[] args" it throws an error about not finding the "args" parameter.

I am trying to call a method w开发者_如何学运维ith the following signature:

public static string MakeWebServiceCall(string methodName, params string[] args)

But it only works if I specify it explicitly like this:

public static string MakeWebServiceCall(string methodName, string place, string type, string token)


Just double-check your JavaScript. It's more likely the culprit than a problem with your C#, as the significance of the params reserved word is non-existant. The argument is still ultimately an array of strings, which is nothing special to JSON. I've just built a quick test page which resulted in absolutely no problems using your method. Try double-checking your syntax against the following:

$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "MyPage.aspx/MakeWebServiceCall",
  data: '{"methodName":"myMethod", "args":["my","array","of","strings"]}',
  dataType: "json"
});

OR if you'd like, stringify a data object using a JavasScript JSON library (native with newer browsers). This method is my personal favorite since I won't have to double-check that I've built my JSON string correctly. Just be sure to enable legacy support for IE7 if you're feeling kind:

var data = {};
data.methodName = "myMethod";
data.args = ["my","array","of","strings"];

$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "MyPage.aspx/MakeWebServiceCall",
  data: JSON.stringify(data),
  dataType: "json"
});

If you're having difficulty with some of the particulars of how these arguments are constructed, you might check out this great resource article from Encosia that I go back to frequently just to remind myself of the basics of consuming web services and page methods with jQuery. It explains a couple of the oddities, including links back to pages which talk about why the contentType encoding is important, as well as information as to why the full JSON string must be provided to the data argument rather than just a JavaScript object.

0

精彩评论

暂无评论...
验证码 换一张
取 消