调用WebMethod传递Dictionary <string,string>作为参数

dex*_*ter 4 .net jquery json webmethod

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

    [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;

    }
}
Run Code Online (Sandbox Code Playgroud)

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

Cal*_*lan 8

要传递字典,您必须使用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!";
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,当你想要调用它时,你可以传递这样的东西.不确定你是否使用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);
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 这里重要的是JSON字符串中的属性与Web方法中的参数名称匹配,在本例中为"values". (4认同)