This project is read-only.

Call WebAPI from MVC View

May 9, 2013 at 10:38 PM
Edited May 9, 2013 at 10:49 PM
Here is my scenario:

I have a WebApi that that has some logic to return json data. I'd like to be able to call this API directly from my MVC view and get some of this json data prefetched directly on the page, and the page will do an async call to get the rest of the data once the client loads.

The problem is that I'd like to have the data the same way that the WebAPI would render it in json, without having to duplicate all the logic to select the formatter, etc. It would be nice to keep the logic in the API without having to split every controller into 2 classes and a helper to format the json.

Does webapi provide any way of doing this? It would be ok to create a helper method to call the action, something like "Invoke ControllerX, ActionY and request the content-type as application/json" and let MVC run the formatters.

The idea is to have something similar to @Html.Action that could call WebAPI routes.
May 18, 2013 at 5:43 AM
Hi nvivo,

There is unfortunately no direct way to do this. The closest way to do this is to make an actual web request to localhost and get the results back as JSON and then render the response content out. The problem is that this isn't very efficient. Though, depending on the application in question, the overhead might not be very significant.

May 25, 2013 at 2:26 PM

I have been working around this, as I'm not very happy with the idea of creating multiple local HTTP requests for each request to my app.

Is this something in the roadmap? Is this being considered for the neat future?
Looks like a basic functionality that MVC had since the beggining, but there is no simple way to do this with WebAPI.