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

标签 .net json jquery 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;

    }
}

我的问题是:如何传递和反序列化 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);
    }
});

关于.net - 调用 WebMethod,传递 Dictionary<string, string> 作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17373452/

相关文章:

javascript - 如何使用 Hammer.js 在 iOS 中禁用垂直滚动?

c# - 如何检查当前用户是否在管理组c#

c# - 滚动到 Microsoft Word 拆分窗口上的范围

.net - Linux 的事务范围

java - JSON中的日期时间字段

json - 从 JSON 文件中删除换行符、制表符和回车符等转义序列字符

.net - 完成后如何让线程报告,VB.NET

java - Spring RequestBody需要加载嵌套的Object

两秒后,jQuery 在鼠标悬停/移出时向上/向下滑动内容 - bug

php - json_encode 在使用 jquery.get() 发布数据时将数组作为字符串返回