I am working on an asp.net MVC 5 application. I created a Web API 2 controller which returns list of medicines. Now I want to display them to view. I created another controller named homecontroller and index action method ( because I think api controller can not have action method). I created index view. In that view I want to show that list of medicines. I followed this link http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api
I am trying this code:
var uri = '/api/Medicines';
$(document).ready(function () {
// Send an AJAX request
$.getJSON(uri)
.done(function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (key, item) {
// Add a list item for the product.
$('<li>', { text: formatItem(item) }).appendTo($('#products'));
});
});
});
but getting 404 in browser console.
This is the Web APi controller method:
public class MedicinesController : ApiController
{
public IEnumerable<Medicine> GetMedicines()
{
Random rnd = new Random();
return medicines.OrderBy(x => rnd.Next()).ToList();
}
}
Route config is:
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Please suggest how to fix this. I need list of medicines in json format.
Thanks