MVC 4 and JsonResult format

牧云@^-^@ 提交于 2019-12-05 23:29:57
Piotr Stapp

Replace your return with:

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

When you return a _JsonResult_ it takes the object and automatically formats this way

    {
        "Property1":"Value1",
        "Property2"_"Value2",
        ...
    }

If you really need other format you could return a _ViewResult_ from your action, add a View and manually write the json. But for this especific format you could use something similar to the Garath's answer.

You can also use this:-

public static KeyValuePair<string,string> KeyValue(YourClass obj)
        {
            return new KeyValuePair<string, string>(obj.id, obj.label);
        }

Before call

Json(result.ConvertAll(i => KeyValue(i)), JsonRequestBehavior.AllowGet);

I do not know if this is possible to do with JsonResult, but you can use Json.NET and it's LINQ support (look on the "LINQ to JSON \ Creating Json", so your method will be something like

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

  var res = new JObject(properties.ToArray());

  return Content(res.ToString(), "application/json");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!