What is the correct way of returning JSON data via API controller in MVC4? I’ve heard that you need to use variable type as function, however I cannot do that because I can’t use .Select(x => new { }) then.
What I do instead is to use dynamic like so
[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;
}
Is this best way of doing this? I’m askin’ because I just started with MVC4 and I don’t want to pick up bad habits early 🙂
You don’t need to use
dynamic, the simple way is to returnobjectfor anonymous type:Or, return
HttpResponseMessage: