Call a WebMethod passing Dictionary<string, string> as parameter

左心房为你撑大大i 提交于 2019-12-01 07:34:48

To pass a dictionary, you have to use a 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!";
    }
}

Then when you want to call it, you can pass something like this. Not sure if you're using jQuery, but here's an example using jQuery's ajax method.

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);
    }
});

Use explict dictionary declaration in case of using jquery ajax syntax. There is difference if you pass the values from c# and check the json being passed using javscript serializer. Same serialized object if you pass using jquery having dictionary then it wont work.

Please use this

DictionaryArguments: [{ 'Key': 'key1', 'Value': 'value1' }, { 'Key': 'key2', 'Value': 'value2' }, { 'Key': 'key3', 'Value': 'value3' }, { 'Key': 'key4', 'Value': 'value4' }],
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!