开发者

How to call ASP.net web method with Array parameter from jQuery Javascript?

开发者 https://www.devze.com 2023-02-24 04:32 出处:网络
I have the following ASP.net web method: [WebMethod] public static string SaveUserNew(string id, string[] roles)

I have the following ASP.net web method:

[WebMethod]
public static string SaveUserNew(string id, string[] roles)
{
 doStuff(id, roles);
}

I'm calling this code from jQuery Javascript code, but I don't know the syntax for passing an array. Ordinarily, I write jQuery code to call web methods that looks like this:

        $.ajax({
             type: "POST",
             url: "someUrl.aspx?webmethod",
             data: '{"foo":"fooValue"}',
             contentType: "application/json;",
             dataType: "json",
            }

Please shed some light on this.

Update: Here is an example of code without arrays that does work:

[WebMethod]
public static string SaveUserNew(string id)
{
    return "0";
}

        var jdata =开发者_Python百科 '{ "id": "3TWR3"}';

        $.ajax({
            type: "POST",
            url: "UserMgmt.aspx/SaveUserNew",
            data: jdata,
            contentType: "application/json;",
            dataType: "json",
            traditional: true                 
            }
        });

My intention is to write some code in a similar style where I pass arrays to my web method.


Passing param to webmethod is a little bit tricky. Try this one

[WebMethod]
public static string GetPrompt(string[] name)
{

    return "Hello " + name[0] + " and " + name[1];
}

jscript

var param = "{'name':['jack', 'jill']}";
var option = {
    error: function(request, status, error) {
        alert(error);
    },
    cache: false,
    success: function(data, status) {
        alert(data.d);
    },
    type: "POST",
    contentType: "application/json; charset=utf-8",
    data: param,
    dataType: "json",
    url: "../Server/ArrayParam.aspx/GetPrompt"
};

$.ajax(option);


You need to
1) assign the data parameter to have an object with the properties id and roles.
2) assign the roles property an array of strings.
3) Set the traditional setting to true while passing options to ajax call.

e.g:

$.ajax({              
    type: "POST",              
    url: "someUrl.aspx?webmethod",              
    data: {
        "id":"1",
        "roles":[
            "Admin",
            "Something",
            "Another Thing"
        ]
    },
    contentType: "application/json;",              
    dataType: "json", 
    traditional: true //#############################   
} 
0

精彩评论

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