In my ASP.net C# code, I have an IEnumerable container filled with objects of an anonymous type (which is loosely based on data from SQL).
Suppose that my code looks something like this:
var uics = entities.getData()
.Select(x => new
{
id = x.id
name = x.name
age = x.age
});
return Json(uics); //Serialize JSON in ASP.net MVC 3
This is very simple. When I serialize this to JavaScript, I get an array of objects, each having fields id, name, and age.
What I would like to do is serialize this data to a JavaScript Object with id as the index, with each object referenced by its index having fields name and age.
How can I accomplish this.
You can create an
IDictionaryand use it as the result of the action:There is no need to explicitly specify the property names for the anonymous type used here, because the compiler defaults those to the name of the property used to provide a value (which in both cases here is the same).