2013-06-28 35 views
3

我試圖簡化從我的WebMethod層返回數據到客戶端的過程,並代表來自客戶端的一組參數Dictionary<string,string>做某事像這樣:調用一個傳遞Dictionary <string,string>作爲參數的WebMethod

[WebMethod(EnableSession = true)] 
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
    public static override ResultObject<List<PatientInfo>> GetResults(Dictionary<string, string> query) 
    { 
     ResultObject<List<PatientInfo>> resultObject = null; 

     if (!query.ContainsKey("finValue")) 
     { 
      resultObject = new ResultObject<List<PatientInfo>>("Missing finValue parameter from the query"); 
     } 

     string finValue = query["finValue"]; 

     if(finValue == null) 
     { 
      resultObject = new ResultObject<List<PatientInfo>>("Missing finValue parameter value from the query"); 
     } 

     var patientData = GetPatientsByFin(finValue); 
     resultObject = new ResultObject<List<PatientInfo>>(patientData); 
     return resultObject; 

    } 
} 

我的問題是:如何傳遞和反序列化Dictionary參數?

回答

7

要傳遞字典,您必須使用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<string, string> 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); 
    } 
}); 
+3

最重要的這裏的事情是,在JSON字符串屬性的Web方法參數名稱相匹配,在這種情況下,「值」。 – Matt

0

在使用jquery ajax語法的情況下使用explict字典聲明。如果你傳遞來自c#的值並檢查使用javscript序列化器傳遞的json是有區別的。相同的序列化對象,如果你通過使用jQuery的字典,那麼它不會工作。

請使用

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