很可能是一个相当琐碎的问题,但我就是找不到合适的答案。我想返回一个“JsonResult”,但实际结果没有任何属性名称。这是我想要实现的一个小例子:
["xbox",
["Xbox 360", "Xbox cheats", "Xbox 360 games"],
["The official Xbox website from Microsoft", "Codes and walkthroughs", "Games and accessories"],
["http://www.xbox.com","http://www.example.com/xboxcheatcodes.aspx", "http://www.example.com/games"]]
是的,一些非常普通的源代码已经存在,但我怀疑这是否有任何相关性。然而,它是:
public JsonResult OpensearchJson(string search)
{
/* returns some domain specific IEnumerable<> of a certain class */
var entites = DoSomeSearching(search);
var names = entities.Select(m => new { m.Name });
var description = entities.Select(m => new { m.Description });
var urls = entities.Select(m => new { m.Url });
var entitiesJson = new { search, names, description, urls };
return Json(entitiesJson, JsonRequestBehavior.AllowGet);
}
最佳答案
给你:
public ActionResult OpensearchJson(string search)
{
/* returns some domain specific IEnumerable<> of a certain class */
var entities = DoSomeSearching(search);
var names = entities.Select(m => m.Name);
var description = entities.Select(m => m.Description);
var urls = entities.Select(m => m.Url);
var entitiesJson = new object[] { search, names, description, urls };
return Json(entitiesJson, JsonRequestBehavior.AllowGet);
}
更新:
对于那些不耐烦在没有实际存储库的情况下进行测试的人:
public ActionResult OpensearchJson(string search)
{
var entities = new[]
{
new { Name = "Xbox 360", Description = "The official Xbox website from Microsoft", Url = "http://www.xbox.com" },
new { Name = "Xbox cheats", Description = "Codes and walkthroughs", Url = "http://www.example.com/xboxcheatcodes.aspx" },
new { Name = "Xbox 360 games", Description = "Games and accessories", Url = "http://www.example.com/games" },
};
var names = entities.Select(m => m.Name);
var description = entities.Select(m => m.Description);
var urls = entities.Select(m => m.Url);
var entitiesJson = new object[] { search, names, description, urls };
return Json(entitiesJson, JsonRequestBehavior.AllowGet);
}
返回:
[
"xbox",
[
"Xbox 360",
"Xbox cheats",
"Xbox 360 games"
],
[
"The official Xbox website from Microsoft",
"Codes and walkthroughs",
"Games and accessories"
],
[
"http://www.xbox.com",
"http://www.example.com/xboxcheatcodes.aspx",
"http://www.example.com/games"
]
]
这正是预期的 JSON。
关于.net - 返回没有属性名称的 Json 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9491119/