Call the web API from MVC Controller to create and submit the model for viewing

Iโ€™m trying to understand many new concepts for me, and I need some clarification on how to best create and transfer my highly typed model from my MVC controller to the Razor view using the web API.

As you can see from 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 html, not necessarily using JavaScript .

When it becomes difficult for me, when I want to use the web API to create the model that I want to use, as if I used it, as I described in the previous paragraph.

Should I call a new HTTPClient to call the web API service from my controller? Do I need to deserialize and format the response? etc...

I always see calls and manipulations from scripts in a view ...

Can someone point me in the right direction?

Thanks.

+6
source share
1 answer

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

Alternatively, you can call the API directly from your view through AJAX, however I'm not sure if you need your controller to do something with the data before it reaches the view.

+8
source

Source: https://habr.com/ru/post/919756/


All Articles