4

I'd like to pass an array to a c# webmethod but don't have a good example to follow. Thanks for any assistance.

Here is what I have so far:

My array:

$(".jobRole").each(function (index) {

    var jobRoleIndex = index;
    var jobRoleID = $(this).attr('id');
    var jobRoleName = $(this).text();

    var roleInfo = {
        "roleIndex": jobRoleIndex,
        "roleID": jobRoleID,
        "roleName": jobRoleName
    };

    queryStr = { "roleInfo": roleInfo };
    jobRoleArray.push(queryStr);

});

My ajax code

  $.ajax({
            type: "POST",
            url: "WebPage.aspx/save_Role",
            data: jobRoleArray,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: false,
            success: function (data) {
                alert("successfully posted data");
            },
            error: function (data) {
                alert("failed posted data");
                alert(postData);
            }

        });

Not sure on the webmethod but here is what I'm thinking:

[WebMethod]
    public static bool save_Role(String jobRoleArray[])
Jayantha Lal Sirisena
  • 21,216
  • 11
  • 71
  • 92
MdeVera
  • 647
  • 5
  • 8
  • 22

3 Answers3

8

You will be passing an array of:

[
    "roleInfo": { 
              "roleIndex": jobRoleIndex, 
               "roleID": jobRoleID, 
               "roleName": jobRoleName 
     },
     "roleInfo": { 
              "roleIndex": jobRoleIndex, 
               "roleID": jobRoleID, 
               "roleName": jobRoleName 
     }, ...
]

And in my opinion, it would be easier if you have a class that matches that structure, like this:

public class roleInfo
{
     public int roleIndex{get;set;}    
     public int roleID{get;set;}
     public string roleName{get;set;}
}

So that when you call your web method from jQuery, you can do it like this:

 $.ajax({
            type: "POST",
            url: "WebPage.aspx/save_Role",
            data: "{'jobRoleArray':"+JSON.stringify(jobRoleArray)+"}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: false,
            success: function (data) {
                alert("successfully posted data");
            },
            error: function (data) {
                alert("failed posted data");
                alert(postData);
            }

        });

And in your web method, you can receive List<roleInfo> in this way:

[WebMethod]
public static bool save_Role(List<roleInfo> jobRoleArray)
{

}

If you try this, please let me know. Above code was not tested in any way so there might be errors but I think this is a good and very clean approach.

Icarus
  • 63,293
  • 14
  • 100
  • 115
  • This seems to work but when I do something like jobRoleArray[0].Index or jobRoleArray[0].RoleID or jobRoleArray[0].RoleName in the webmethod I don't see any data. – MdeVera Sep 25 '11 at 21:53
  • Have you checked that the data is there when the ajax call is made? – James Hay Sep 29 '11 at 01:44
4

I have implement something like this before which is passing an array to web method. Hope this will get you some ideas in solving your problem. My javascript code is as below:-

 function PostAccountLists() {

        var accountLists = new Array();

        $("#participantLists input[id*='chkPresents']:checked").each(function () {
            accountLists.push($(this).val());
        });

        var instanceId = $('#<%= hfInstanceId.ClientID %>').val();

        $.ajax({
            type: "POST",
            url: "/_layouts/TrainingAdministration/SubscriberLists.aspx/SignOff",
            data: "{'participantLists': '" + accountLists + "', insId : '" + instanceId + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                AjaxSucceeded(msg);
            },
            error: AjaxFailed
        });
    }

In the code behind page (the web method)

 [WebMethod]
    public static void SignOff(object participantLists, string insId)
    {
        //subscription row id's
        string[] a = participantLists.ToString().Split(',');
        List<int> subIds = a.Select(x => int.Parse(x)).ToList<int>();

        int instanceId = Convert.ToInt32(insId);

The thing to notice here is in the web method, the parameters that will receive the array from the ajax call is of type object.

Hope this helps.

EDIT:- according to your web method, you are expecting a value of type boolean. Here how to get it when the ajax call is success

   function AjaxSucceeded(result) {
        var res = result.d;
        if (res != null && res === true) {
            alert("succesfully posted data");
        }
    }

Hope this helps

Agamand The True
  • 832
  • 2
  • 10
  • 24
  • would you have more of the webmethod completed? I can't seem to read any data at all. However, the method is called and I have tried the sample you provided. Just can't seem to get the data out. thanks for any help. – MdeVera Sep 26 '11 at 03:02
  • thank you agamand but I'm at a point where I need to deserialize my object but can't seem to get the data out clean. I'm following your sample: string[] a = participantLists.ToString().Split(','); List subIds = a.Select(x => int.Parse(x)).ToList(); But how do you get to see each element individually? Thanks so much for any help. – MdeVera Sep 29 '11 at 23:27
0

Adding this for the ones, like MdeVera, that looking for clean way to send array as parameter. You can find the answer in Icarus answer. I just wanted to make it clear:

JSON.stringify(<your array cames here>)

for example, if you would like to call a web page with array as parameter you can use the following approach:

"<URL>?<Parameter name>=" + JSON.stringify(<your array>)
Asaf
  • 477
  • 6
  • 6