brian4342
brian4342

Reputation: 1253

Use a dictionary type in Javascript [Ajax]

I am building an ASP.NET MVC application It currently has a button that once clicked does an Ajax call to the controller as so:

function getData() {
    $.ajax({
        url: "/Home/GetData/",
        type: "POST",
        contentType: 'application/json',
        success: function (data){
            //need to do stuff here
        }
    });
}

The controller then initializes a class, converts it to XML and then converts that to the following dictionary (There is a reason for this):

public ActionResult GetData()
    {
        List<People> peeps = GetPeeps();

        string xml = ToXml(peeps);
        Dictionary<string,List<string>> stuff = ToDictionary(xml);

        return Json(stuff);
    }

I would like to be able to 'Do stuff' with this data client side with javascript.

The APIs I have to work with Server side return XML data. The APIs I have to work with Client side require string arrays. (Hence the conversions)

Is there a way to use the dictionary i've defined above client side? Could someone perhaps expand from this (if possible) to add to the ajax call a small method that prints the contents of the dictionary to a message box? just to give me a starting point from how to use the dictionary in javascript.

Thanks in advance

Upvotes: 0

Views: 5450

Answers (1)

vbn
vbn

Reputation: 799

You can try in the ajax call as follow:

function getData() {
    $.ajax({
        url: "/Home/GetData/",
        type: "POST",
        contentType: 'application/json',
        success: function (data){
            console.log(data.key1); // value for key1
            //or to list all values
            for(var key in data){
                 console.log(data[key]);
            }
        }
    });
}

Controller (for explanation purposes):

public ActionResult GetData()
{
    //List<People> peeps = GetPeeps();

    //string xml = ToXml(peeps);
    //Dictionary<string,List<string>> stuff = ToDictionary(xml);
    Dictionary<string,List<string>> stuff = new Dictionary<string, List<string>>
        { 
                {"key1", new List<string> {"a", "b", "c"}},
                {"key2", new List<string> {"d", "e", "f"}},
        };

    return Json(stuff);
}

I hope this is clear enough. Let me know how you go :)

Upvotes: 2

Related Questions