gpt4 book ai didi

asp.net-mvc - MVC 4 和 JsonResult 格式

转载 作者:行者123 更新时间:2023-12-01 10:54:43 26 4
gpt4 key购买 nike

这段代码的结果格式有问题

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);
}

这会返回一个 json:

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

但我需要一个格式如下的json:

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

我能做什么?

非常感谢,对不起我的英语。

最佳答案

将您的返回替换为:

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

关于asp.net-mvc - MVC 4 和 JsonResult 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15940397/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com