调用WebMethod,将Dictionary 作为参数传递

我正在尝试简化将数据从WebMethod层返回到客户端的过程,并在Dictionary表示来自客户端的参数集,以执行以下操作:

  [WebMethod(EnableSession = true)] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public static override ResultObject<List> GetResults(Dictionary query) { ResultObject<List> resultObject = null; if (!query.ContainsKey("finValue")) { resultObject = new ResultObject<List>("Missing finValue parameter from the query"); } string finValue = query["finValue"]; if(finValue == null) { resultObject = new ResultObject<List>("Missing finValue parameter value from the query"); } var patientData = GetPatientsByFin(finValue); resultObject = new ResultObject<List>(patientData); return resultObject; } } 

我的问题是:如何传递和反序列化Dictionary参数?

要传递字典,您必须使用WebService。

 [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] [ScriptService] public class TestService : System.Web.Services.WebService { [WebMethod] public String PostBack(Dictionary values) { //You should have your values now... return "Got it!"; } } 

然后,当你想要调用它时,你可以传递这样的东西。 不确定你是否使用jQuery,但这是一个使用jQuery的ajax方法的例子。

 var valueObject = {}; valueObject['key1'] = "value1"; valueObject['secondKey'] = "secondValue"; valueObject['keyThree'] = "3rdValue"; $.ajax({ url: 'TestService.asmx/PostBack', type: 'POST', dataType: 'json', contentType: 'application/json; charset=utf-8', data: JSON.stringify({ values: valueObject }), success: function (data) { alert(data); }, error: function (jqXHR) { console.log(jqXHR); } }); 

在使用jquery ajax语法的情况下使用explict字典声明。 如果从c#传递值并检查使用javscript serializer传递的json,则会有区别。 相同的序列化对象,如果您使用具有字典的jquery传递然后它不会工作。

请用这个

 DictionaryArguments: [{ 'Key': 'key1', 'Value': 'value1' }, { 'Key': 'key2', 'Value': 'value2' }, { 'Key': 'key3', 'Value': 'value3' }, { 'Key': 'key4', 'Value': 'value4' }],