0

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

brian4342
  • 1,265
  • 8
  • 33
  • 69

1 Answers1

2

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 :)

vbn
  • 789
  • 1
  • 6
  • 16
  • How would I print out the key if its not know at compile time? so far the for loop prints out the values but how can this be changed to also print out the keys? – brian4342 Apr 20 '14 at 10:26
  • The key variable in the for loop is actually the key in the dictionary. Did that answer your question? – vbn Apr 22 '14 at 12:37