Sashko  Chehotsky
Sashko Chehotsky

Reputation: 408

Send data from ajax to c# server

I've created a dictionary on cliend side and want to send it on sever side. In my script, dictionary is created correctly, but I'm not sure abount my ajax code.

$("#btnSubmit").click(function () {
        var sendList = new Array();
        var elems = $(".elemValue");
        $.each(elems, function (key, value) {
            if (value.attributes.elemName.nodeValue != "PhotoImg") {
                sendList[value.attributes.elemName.nodeValue] = value.attributes.value.nodeValue;
            }
        });

        var data = JSON.stringify({dict : sendList});

        $.ajax({
            type: "GET",
            url: "dataloader.aspx/GetData",
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (result){
                alert(result.d);
            }
        });
        });

On server side I wrote

[System.Web.Services.WebMethod]
    public static string GetData(Dictionary<string,string> dict)
    {
        Dictionary<string, string> serverDict = new Dictionary<string, string>();
        serverDict = dict;
        string result = "";
        foreach (var value in dict)
        {
            result += "The key is:" + value.Key + "The value is:" + value.Value;
        }

        return result;
    }

Where are my mistakes, and how can I fix them? Help, please=)

Upvotes: 0

Views: 1121

Answers (2)

Spencer Ruport
Spencer Ruport

Reputation: 35107

I don't think it's possible to create a Dictionary from JSON. At least not without a lot of work. I would try changing it from a Dictionary to a List<KeyValuePair<string,string>> and see if it deserializes for you.

Reference for KeyValuePair

Once you've done that if you still need the Dictionary you can convert it fairly easily.

var Dictionary = new Dictionary<string,string>();
foreach(var KVP in List) Dictionary.Add(KVP.Key, KVP.Value);

Upvotes: 1

Andrei
Andrei

Reputation: 56688

Couple of things here:

  1. You need to allow GET verb explicitly:

    [System.Web.Services.WebMethod]
    [System.Web.Script.Services.ScriptMethod(UseHttpGet=true)]
    
  2. You are returning plain text from the server, which means that this line:

    dataType: "json"
    

    won't let jQuery parse the response correctly. You should either remove this line, or build response in JSON format.

Upvotes: 0

Related Questions