Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling web API from MVC Controller to build and pass model to view

I am trying to grasp many concepts that are new to me and I need some clarifications on the best way to create and pass my strongly typed model from my MVC Controller to its Razor view using a Web API.

As seen in many examples, you usually create your model from some repository and then pass it to the view (strongly typed or not) and then use the Razor syntax which gives you access to your model to build the html not necessarily having to use JavaScript.

Where things get complicated for me is when I want to make use of the Web API to create the model I want to use just like I would use it as I describe in the previous paragraph.

Should I call the new HTTPClient to call the Web API service from within my controller? Will I need to deserialize and format the response? etc...

I always see calls and manipulations from scripts within the view...

Could someone point me to the right direction?

Thanks.

like image 760
jbrabant Avatar asked Jul 05 '12 12:07

jbrabant


1 Answers

If your WebAPI is a separate endpoint i.e. not part of your existing site, then yes you will have to send a HttpWebRequest from inside your controller and then serialize the data from the response and pass that into your view.

Alternatively you could call the API directly from inside your view via AJAX, however, I am not sure if you need your controller to do something with the data before it comes down to the view.

like image 116
James Avatar answered Oct 13 '22 05:10

James