Reputation: 26511
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 :)
Upvotes: 1
Views: 4495
Reputation: 75326
You don't need to use dynamic
, the simple way is to return object
for anonymous type:
[HttpGet]
public object 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;
}
Or, return HttpResponseMessage
:
[HttpGet]
public HttpResponseMessage 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 Request.CreateResponse(HttpStatusCode.OK, items);
}
Upvotes: 1
Reputation: 10532
Built-in function Controller.Json
(MSDN) can do what you want, i.e. assuming your code resides inside controller class:
[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);
}
If you want to use it in GET requests, then you should use overload which accepts JsonRequestBehavior
flags as parameter and specify JsonRequestBehavior.AllowGet
for that parameter.
Upvotes: 3