dexter
dexter

Reputation: 7213

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

I am trying to streamline the process of returning the data from my WebMethod layer to the client and represent the set of parameters in coming from the client in a Dictionary<string,string> to do something like this:

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

    }
}

My question is: how do I pass and de-serialize the Dictionary parameter?

Upvotes: 5

Views: 8659

Answers (2)

Mahesh Malpani
Mahesh Malpani

Reputation: 2009

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' }],

Upvotes: 0

Callan
Callan

Reputation: 475

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

Upvotes: 9

Related Questions