gpt4 book ai didi

c# - 使用 MVC4 返回值的正确方法

转载 作者:太空宇宙 更新时间:2023-11-03 21:56:01 26 4
gpt4 key购买 nike

在 MVC4 中通过 API Controller 返回 JSON 数据的正确方法是什么?我听说您需要将变量类型用作函数,但是我不能那样做,因为我不能使用 .Select(x => new { }) 然后。

我做的是像这样使用dynamic

[HttpGet]
public dynamic List() // Not List<Item>
{
var items = _db.Items.OrderBy(x => x.ID).Select(x => new
{
ID = x.ID,
Title = x.Title,
Price = x.Price,
Category = new {
ID = x.Category.ID,
Name = x.Category.Name
}
});

return items;
}

这是最好的方法吗?我问是因为我刚开始使用 MVC4,我不想早早养成坏习惯 :)

最佳答案

内置函数 Controller.Json ( MSDN ) 可以做你想做的事,即假设你的代码驻留在 Controller 类中:

[HttpGet]
public dynamic List() // Not List<Item>
{
var items = _db.Items.OrderBy(x => x.ID).Select(x => new
{
ID = x.ID,
Title = x.Title,
Price = x.Price,
Category = new {
ID = x.Category.ID,
Name = x.Category.Name
}
});

return Json(items, JsonRequestBehavior.AllowGet);
}

如果你想在 GET 请求中使用它,那么你应该使用接受 JsonRequestBehavior 标志作为参数的重载,并为该参数指定 JsonRequestBehavior.AllowGet

关于c# - 使用 MVC4 返回值的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12261710/

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