Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I want to pass a javascript string array to a C# webmethod via jQuery (POST):

$.ajax({
    type: "POST",       //GET or POST or PUT or DELETE verb          
    url: PageURL + 'ChangeColor',       // Location of the service
    data:   "{ 'OriginalColorHex': '" + JSON.stringify(clipartOriginalColorsHex) + "','ModifiedColorHex':'" + JSON.stringify(clipartModifiedColorsHex) +
            "','OriginalColorRGB': '" + JSON.stringify(clipartOriginalColorsRGB) + "','ModifiedColorRGB':'" + JSON.stringify(clipartModifiedColorsRGB) +
            "','fileName':'" + clipartFileName + "' }",
    contentType: "application/json; charset=utf-8",     // content type sent to server
    dataType: "json",   //Expected data format from server
    processdata: true,  //True or False      
    traditional: true,          
    success: function (result) {//On Successful service call
        console.log(result);
    }
});   

Data going in ajax call looks like this

{ 'OriginalColorHex': '["#000000","#006565","#cccc99"]','ModifiedColorHex':'["#3366CC","#cc5500","#3366cc"]','OriginalColorRGB': '["rgb(0,0,0)","rgb(0,101,101)","rgb(204,204,153)"]','ModifiedColorRGB':'["rgb(51, 102, 204)","rgb(204, 85, 0)","rgb(51, 102, 204)"]','fileName':'179.svg' }

C# Webmethod

 [WebMethod]
 public static string ChangeClipartColor(string[] OriginalColorHex, string[] ModifiedColorHex, string[] OriginalColorRGB, string[] ModifiedColorRGB, string fileName)
 {
     // Code Here
 }

Error

{"Message":"Cannot convert object of type \u0027System.String\u0027 to type \u0027System.String[]\u0027","StackTrace":"   at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object\u0026 convertedObject)\r\n   at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object\u0026 convertedObject)\r\n   at System.Web.Script.Services.WebServiceMethodData.StrongTypeParameters(IDictionary`2 rawParams)\r\n   at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary`2 parameters)\r\n   at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)\r\n   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}
share|improve this question

4 Answers 4

up vote 8 down vote accepted

Quick Fix

JSON arrays do not need to be in quotes. This is valid JSON:

{
    "OriginalColorHex": [
        "#000000",
        "#006565",
        "#cccc99"
    ]
}

Try validating your JSON with a tool like JSONLint to make sure it's valid. The WebMethod should be able to accept a string array just fine.

A slightly better method

Instead of building your JSON as a string, build an object and then let JavaScript handle the conversion for you:

var clipartOriginalColorsHex = ['#000000','#006565','#cccc99'];
var clipartModifiedColorsHex = ['#3366CC','#cc5500','#3366cc'];
var clipartOriginalColorsRGB = ['rgb(0,0,0)','rgb(0,101,101)','rgb(204,204,153)'];
var clipartModifiedColorsRGB = ['rgb(51, 102, 204)','rgb(204, 85, 0)','rgb(51, 102, 204)'];
var fileName = '179.svg';

var myData = {
    OriginalColorHex: clipartOriginalColorsHex,
    ModifiedColorHex: clipartModifiedColorsHex,
    OriginalColorRGB: clipartOriginalColorsRGB,
    ModifiedColorRGB: clipartModifiedColorsRGB,
    fileName: fileName
};

$.ajax({
    type: "POST",       //GET or POST or PUT or DELETE verb          
    url: PageURL + 'ChangeColor',       // Location of the service
    data:   JSON.stringify(myData),
    contentType: "application/json; charset=utf-8",     // content type sent to server
    dataType: "json",   //Expected data format from server
    processdata: true,  //True or False      
    traditional: true,          
    success: function (result) {//On Successful service call
        console.log(result);
    }
});

Much cleaner, less error-prone, and easier to test. Here's a fiddle to demonstrate.

share|improve this answer

Because the values are not an array. Remove the quotes around the strings that look like an array.

{ 'OriginalColorHex': ["#000000","#006565","#cccc99"],'ModifiedColorHex':["#3366CC","#cc5500","#3366cc"],'OriginalColorRGB': ["rgb(0,0,0)","rgb(0,101,101)","rgb(204,204,153)"],'ModifiedColorRGB':["rgb(51, 102, 204)","rgb(204, 85, 0)","rgb(51, 102, 204)"],'fileName':'179.svg' }
share|improve this answer

You are passing a string ('["#000000","#006565","#cccc99"]') into a string[]. Get rid of the single quotes around your array's. This should do it:

$.ajax({
type: "POST",       //GET or POST or PUT or DELETE verb          
url: PageURL + 'ChangeColor',       // Location of the service
data:   "{ 'OriginalColorHex': " + JSON.stringify(clipartOriginalColorsHex) + ",'ModifiedColorHex':" + JSON.stringify(clipartModifiedColorsHex) +
        ",'OriginalColorRGB': " + JSON.stringify(clipartOriginalColorsRGB) + ",'ModifiedColorRGB':" + JSON.stringify(clipartModifiedColorsRGB) +
        ",'fileName':" + clipartFileName + " }",
contentType: "application/json; charset=utf-8",     // content type sent to server
dataType: "json",   //Expected data format from server
processdata: true,  //True or False      
traditional: true,          
success: function (result) {//On Successful service call
    console.log(result);
}

});

share|improve this answer

You could make your life easier by waiting to stringify your data after you've put it all together.

var data = {
    OriginalColorHex: clipartOriginalColorsHex,
    ModifiedColorHex: clipartModifiedColorsHex,
    OriginalColorRGB: clipartOriginalColorsRGB,
    ModifiedColorRGB: clipartModifiedColorsRGB,
    fileName: clipartFileName
};

$.ajax({
    type: "POST", // GET or POST or PUT or DELETE verb          
    url: PageURL + 'ChangeColor', // Location of the service
    data: JSON.stringify(data),
    contentType: "application/json; charset=utf-8", // content type sent to server
    dataType: "json", // Expected data format from server
    processdata: true, // True or False      
    traditional: true,          
    success: function (result) { // On Successful service call
        console.log(result);
    }
});
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.