Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass an array in jquery via ajax to a c# webmethod

Tags:

jquery

asp.net

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[])
like image 976
MdeVera Avatar asked Dec 16 '22 09:12

MdeVera


2 Answers

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.

like image 108
Icarus Avatar answered Dec 21 '22 23:12

Icarus


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

like image 38
Agamand The True Avatar answered Dec 22 '22 00:12

Agamand The True