簡體   English   中英

通過jQuery AJAX將字符串數組傳遞給C#WebMethod

[英]pass string array via jQuery AJAX to C# WebMethod

我想通過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"
}

快速解決

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

更清潔,更不容易出錯,更容易測試。 這是一個小提琴演示。

因為值不是數組。 刪除看起來像數組的字符串周圍的引號。

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

您正在將一個字符串('[“#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);
}

});

通過等待將數據整合在一起后,您可以讓您的生活更輕松。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM