调用 WebMethod,传递 Dictionary 作为参数

2023-11-23

我正在尝试简化将数据从 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;

    }
}

我的问题是:如何传递和反序列化 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<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);
    }
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

调用 WebMethod,传递 Dictionary 作为参数 的相关文章

随机推荐