javascript - Can I output JSON where the ID is the key rather than it being an array in ASP.NET MVC (C#) -


so in asp.net mvc have controller action this:

public jsonresult people() {     var people = db.people.tolist();     return json(people); } 

and when ajaxed return this:

[   {     "id": 1,     "name": "john smith"   },   {     "id": 2,     "name": "daryl jackson"   } ] 

however, i'm looking not json array of records shown above, more json object ids of each record key , record nested value, so:

{   1: {     "name": "john smith"   },   2: {     "name": "daryl jackson"   } } 

my initial thought create dictionary in c# similar structure , pass json() method not know how handle dictionary objects.

is there way achieve kind of structure in c#? i'm having resort restructuring on client-side or using loops find record id i'm searching for. it'd nicer if record id in javascript. going wrong? i'm new asp.net mvc environment.

any suggestions appreciated. thank :)

you can use 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 people table has id , firstname column, code return json dictionary table data

{ "101" : {"id":101,"name":"john"},"102":{"id":102,"name":"darryl"} } 

using json metod, cannot serialize dictionary dictionary key of type int, need explicitly convert int value string.

if want specific user userid, can use dictionary style syntax yourjsobject[key]

 var url="putrelativeurltoreportscorehere";  $.getjson(url, function(data) {         console.log(data);         //get user key 102         console.log(data[102]);  }); 

Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

java.lang.NoClassDefFoundError When Creating New Android Project -

Decoding a Python 2 `tempfile` with python-future -