jotero jotero - 2 months ago 20
JSON Question

MVC 4 and JsonResult format

have a problem with the result format of this code

public JsonResult getCategorias(int? id)
{
var res = from c in db.Categorias
where (( id.HasValue && c.CategoriaPadre == id.Value) || (!id.HasValue && c.CategoriaPadre == null))
select new { id = c.Id, label = c.Descripcion };

return this.Json(res, JsonRequestBehavior.AllowGet);
}


this return a
json
:

[{"id":21,"label":"Marketing3"},{"id":22,"label":"Marketing4"}]


But i need a
json
with this format:

{"21":"Marketing3","22":"Marketing4"}


What can i do?

Thanks a lot and sorry my english.

Answer

Replace your return with:

var dictionary = res.ToDictionary(v => v.id, v => label);
 return this.Json(dictionary, JsonRequestBehavior.AllowGet);