12

I'm trying to pass an array of string parameters to a C# ASP.NET web service using jQuery Ajax. Here is my sample web method. Note that the function accepts a variable number of parameters. I get a 500 Internal Server Error in Chrome's javascript console when I run the jquery. I'm using jquery 1.6.2 and .NET3.5

[WebMethod]
public string Concat(params string[] arr)
{
    string result = "";
    for (int i = 0; i < arr.Length; i++)
    {
        result += arr[i];
    }
    return result;
}

Here is the jquery:

$(document).ready(function() {

    var myCars=new Array(); 
    myCars[0]="Saab";      
    myCars[1]="Volvo";
    myCars[2]="BMW";

    $.ajax({
        type: "POST",
        url: "WebService.asmx/Concat",
        data: {arr: myCars},        //can't figure out what to put here     
        success: onSuccess,
        Error: onError
    });
});

function onSuccess()
{
    alert("testing");
}

function onError() 
{
    alert("fail");
}

</script>

Any help is appreciated!

weir
  • 3,914
  • 2
  • 23
  • 36
orikon
  • 253
  • 2
  • 8
  • 18
  • Perhaps you could [serialize](http://api.jquery.com/serialize/) the array and then unserialize it in the service. – Shomz Nov 01 '11 at 19:52

1 Answers1

24

Revised server-side code:

[WebMethod]
public string Concat(List<string> arr)
{
    string result = "";
    for (int i = 0; i < arr.Count; i++)
    {
        result += arr[i];
    }
    return result;
}

Also, add this above your WebService class declaration:

[System.Web.Script.Services.ScriptService]

Revised client-side code:

    $(document).ready(function () {

        var myCars = new Array();
        myCars[0] = "Saab";
        myCars[1] = "Volvo";
        myCars[2] = "BMW";

        $.ajax({
            type: "POST",
            url: "WebService.asmx/Concat",
            data: JSON.stringify({ arr: myCars }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: onSuccess,
            failure: onError
        });
    });

    function onSuccess(response) {
        alert(response.d);
    }

    function onError() {
        alert("fail");
    }

Also, add above that script block a reference to JSON2, such as:

<script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>

Notes:

  • I have tested this under .NET 4 and using jQuery 1.6.4.
  • Make sure you keep the client and server variable names in sync:
    public string Concat(List<string> arr)
    data: JSON.stringify({ arr: myCars })
weir
  • 3,914
  • 2
  • 23
  • 36
  • I'm now trying to extend this to use with jqGrid but it's not working, any ideas? I've opened another question here: http://stackoverflow.com/questions/7975662/passing-array-of-strings-to-jqgrid – orikon Nov 02 '11 at 05:28
  • I had to make my server side method as static inorder to make it work. example: public static string Concat(List arr) – Vimalan Jaya Ganesh Oct 05 '15 at 20:31