通过jQuery AJAX将字符串数组传递给C#WebMethod

时间:2015-04-21 14:37:09

标签: javascript c# jquery .net ajax

我想通过jQuery(POST)将JavaScript字符串数组传递给C#WebMethod:

$.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);
    }
});   

ajax调用中的数据如下所示

{ '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
}

错误

{
   "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"
}

4 个答案:

答案 0 :(得分:12)

快速修复

JSON数组不需要引号。这是有效的JSON:

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

尝试使用JSONLint之类的工具验证您的JSON,以确保它有效。 WebMethod应该能够接受一个字符串数组。

稍微好一点的方法

不是将JSON构建为字符串,而是构建一个对象,然后让JavaScript为您处理转换:

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);
    }
});

更清洁,更不容易出错,更容易测试。这是一个fiddle来演示。

答案 1 :(得分:4)

因为值不是数组。删除看起来像数组的字符串周围的引号。

{ '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' }

答案 2 :(得分:3)

您正在传递一个字符串(' ["#000000","#006565","#cccc99"]')进入一个字符串[]。摆脱阵列周围的单引号。这应该这样做:

$.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);
}

});

答案 3 :(得分:1)

您可以在将所有数据汇总到一起后等待字符串化,从而让您的生活更轻松。

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);
    }
});