在 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。
