Web API で JSON を取得する実装例です。
View:
<input type="button" id="apiButton" class="btn" value="Web Api Test" /> <script> function asyncCall() { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if ((xhr.readyState === 4) && (xhr.status === 200)) { var json = xhr.response; console.log(json); } } xhr.open("GET", "/api/values", true); xhr.send(null); } var button1 = document.getElementById("apiButton"); button1.addEventListener("click", asyncCall, false); </script>
Controller:
public class Item { public int Id { get; set; } public string Name { get; set; } public DateTime RegisteredOn { get; set; } public int CategoryId { get; set; } } public class ValuesController : ApiController { // GET api/values public IEnumerable<Item> Get() { List<Item> items = new List<Item>(); items.Add(new Item { Id = 1, Name = "Toshihiko", CategoryId = 1, RegisteredOn = DateTime.Today }); items.Add(new Item { Id = 2, Name = "Takashi", CategoryId = 1, RegisteredOn = DateTime.Today }); return items; } }