简体   繁体   中英

showing json from Web API controller on Razor view

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

Link '/api/Medicines' will work if route is configured similar to

routes.MapHttpRoute(
    name: "API Default",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

But if you have it like this (there both versions in tutorial)

routes.MapHttpRoute(
    name: "ActionApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

you have to also specify Action name in uri '/api/Medicines/Medicines'.

UPDATE

I've created new MVC 5 project with WebApi and everithing worked without any problems and hacks. You cant try to compare with your solution - test repo on github .

If you have stadard route configuration and not use any areas etc your uri should be

var uri = '/Medicines/GetMedicines'

And as Joanvo said you migth be need allowGet setting in return. Like this:

return Json(medicines.OrderBy(x => rnd.Next()), JsonRequestBehavior.AllowGet);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM