Ad

Can I Output JSON Where The ID Is The Key Rather Than It Being An Array In ASP.NET MVC (C#)

- 1 answer

So in ASP.NET MVC I have a Controller action somewhat like this:

public JsonResult People()
{
    var people = db.People.ToList();
    return Json(people);
}

and when ajaxed this will return something like this:

[
  {
    "ID": 1,
    "Name": "John Smith"
  },
  {
    "ID": 2,
    "Name": "Daryl Jackson"
  }
]

However, what I'm looking for is not a JSON array of the records as shown above, but more a JSON object where the IDs of each record is the key and then the record nested as the value, like so:

{
  1: {
    "Name": "John Smith"
  },
  2: {
    "Name": "Daryl Jackson"
  }
}

My initial thought would be to create a Dictionary in C# similar to this structure and pass it into Json() however the method does not know how to handle Dictionary objects.

Is there a way to achieve this kind of structure in C#? Currently I'm having to resort to restructuring it on the client-side or using loops to find a record with the ID I'm searching for. It'd be nicer if I could just get the record by ID in Javascript. Am I going about this all wrong? I'm new to the ASP.NET MVC environment.

Any suggestions would be greatly appreciated. Thank you :)

Ad

Answer

You can use the ToDictionary() extension method.

public ActionResult People()
{
   var peopleDictionary = db.People
                          .Select(x=> new {  Id = x.Id, Name= x.FirstName})
                          .ToDictionary(d => d.Id.ToString(), p => p);

   return Json(peopleDictionary, JsonRequestBehavior.AllowGet);
}

Assuming your People table has an Id and FirstName column, this code will return a json dictionary like this from your table data

{ "101" : {"Id":101,"Name":"John"},"102":{"Id":102,"Name":"Darryl"} }

Using the Json metod, You cannot serialize a dictionary where the dictionary key is of type int, so you need to explicitly convert your int value to a string.

If you want to get a specific user from the a userId, you can use the dictionary style syntax yourJsObject[key]

 var url="PutRelativeUrlToReportScoreHere";
 $.getJSON(url, function(data) {
        console.log(data);
        //Get the User with Key 102
        console.log(data[102]);
 });
Ad
source: stackoverflow.com
Ad