将参数作为JSON对象传递给WebMethod
本文关键字:WebMethod 对象 JSON 参数 | 更新日期: 2023-09-27 18:00:50
当我将参数传递给WebmMethod
时,会出现各种错误。以下是我的各种尝试和我得到的错误:
globalData
是一个数组,mapping
是一个可以反序列化为List<Mapping>
的数组,selectedFund
是一个整数。
C#WebMethod
[WebMethod]
public static void ProcessData(string data, List<Mapping> mapping, int selectedFund)
{
//blah blah
}
尝试1
var payload = new Object();
payload.data = globalData;
payload.mapping = chosenMappings;
payload.selectedFund = $selectedFund.val();
$.ajax({
//...etc
data: JSON.stringify(payload),
contentType: "application/json; charset=utf-8",
}
错误:System.String
不支持数组的序列化。
尝试2
$.ajax({
//... etc...
data: {
data: JSON.stringify(globalData),
mapping: JSON.stringify(chosenMappings),
selectedFund: $selectedFund.val()
},
contentType: "application/json; charset=utf-8",
错误:Json基元无效
您在jQuery JSON帖子中缺少内容类型:
contentType: "application/json; charset=utf-8",
检查这篇文章
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
想好了。。。我需要做两次JSON.stringify()
。一次在外面,一次在里面。。。
contentType: "application/json; charset=utf-8",
type: 'POST',
dataType: "json",
//data: JSON.stringify(payload),
data: JSON.stringify({
data: JSON.stringify(globalData),
mapping: JSON.stringify(chosenMappings),
selectedFund: $selectedFund.val()
}),