web-dev-qa-db-ja.com

jQuery経由で文字列配列を渡すAJAX C#WebMethodに

JavaScript文字列配列をjQuery(POST)を介して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"
}
15
Shaggy

クイックフィックス

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 です。

12
Nate Barbettini

値が配列ではないためです。配列のように見える文字列を囲む引用符を削除します。

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

文字列( '["#000000"、 "#006565"、 "#cccc99"]')をstring []に渡しています。配列の周りの単一引用符を取り除きます。これはそれを行うはずです:

$.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
Nils O

すべてをまとめた後、データを文字列化するのを待つことで、人生をより簡単にすることができます。

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