Czyli jednym słowem chcesz zwrócić z jakiejś akcji rezultat w postaci json, żeby potem móc sobie to ajaxem pobrać?
To tu nie trzeba żadnego ApiController
. Możesz użyć zwykłego kontrolera, i jego metody pomocniczej Json()
zwracając JsonResult
, na przykład mając model:
namespace WebFun1.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public int Amount { get; set; }
}
}
i akcje:
using System.Collections.Generic;
using System.Web.Mvc;
using WebFun1.Models;
namespace WebFun1.Controllers
{
public class ProductsController : Controller
{
public JsonResult Index()
{
var listOfProducts = new List<Product>
{
new Product { Id = 1, Name = "Banan", Amount = 31, Price = 2 },
new Product { Id = 2, Name = "Frytki", Amount = 20, Price = 5 },
new Product { Id = 3, Name = "Paczek", Amount = 10, Price = 2 },
new Product { Id = 4, Name = "Pizza", Amount = 3, Price = 40 }
};
return Json(listOfProducts, JsonRequestBehavior.AllowGet);
}
}
Po wykonaniu tej akcji dostajemy ładny wynik:
[
{
"Id":1,
"Name":"Banan",
"Price":2,
"Amount":31
},
{
"Id":2,
"Name":"Frytki",
"Price":5,
"Amount":20
},
{
"Id":3,
"Name":"Paczek",
"Price":2,
"Amount":10
},
{
"Id":4,
"Name":"Pizza",
"Price":40,
"Amount":3
}
]