使用Dictionary <string,int =“”>参数</string,>将对象传递给WebMethod

时间:2013-02-22 11:35:50

标签: javascript jquery asp.net json json.net

我有这个错误 无法将类型为\ u0027System.String \ u0027的对象转换为类型\ u0027System.Collections.Generic.Dictionary 2[System.String,System.Int32]\u0027","StackTrace":" at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)\r\n at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)\r\n at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToType(Object o, Type type, JavaScriptSerializer serializer)\r\n at System.Web.Script.Services.WebServiceMethodData.StrongTypeParameters(IDictionary 2 rawParams)\ r \ n在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在System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context,WebServiceMethodData methodData)“,”ExceptionType“:”System.InvalidOperationException

当我使用Dictionary

将数组传递给WebMethod时

1 个答案:

答案 0 :(得分:0)

如果它是webapi的web方法,那么你不能将列表或字典类型的对象传递给方法,你只会想传递字符串参数,传递这个对象需要将它们序列化为字符串然后你可以反序列化使用该字符串将它们返回到列表或字典对象。

Webmethod使用代码:

Dictionary<string,int> objstring = new Dictionary<string,int>
var serializer = new JavaScriptSerializer();
var serializedstring = serializer.Serialize(objstring);

然后在参数中传递serializedstring。

在反序列化时,只需在webapi方法中从序列化程序对象调用deserialize方法。

我希望这会对你有所帮助。