'How to consume ASP.NET Core WebAPI using MVC Razor view

I am trying to build a web application using ASP.NET Core Web API and MVC with Razor views.

Here is my code for the TopicController:

  public async Task'<'IResult'>' Index()
  {
      return Results.Ok(await _Data.GetAllTopics());
  }

Output of this controller is:

{ 
    "value": [
                 { 
                   "id": 1,
                   "topicName": "ACCESS MODIFIER",
                   "videoName": null,
                   "videoURL":null
                 },
                 {
                   "id": 2,
                   "topicName": "GENERICS",
                   "videoName": null,
                   "videoURL": null
                 }
             ],
    "statusCode": 200,
    "contentType": null
}

I am able display data if the return type of Index() is IActionResult for a complex object. But not sure how to interpret result from above Index() function.

I am new to front end, any help would be appreciated.



Solution 1:[1]

Start by nuking Results.Ok from the code because this returns JSON. Change the return type of the action method to ActionResult, be sure to return View, then build the Razor page.

Solution 2:[2]

I was able to make my code work. Instead of returning JSON I am retuning a view. However I have to do a local mapping of the objects.

public async Task<IActionResult> Index()
{

List<Models.Topic> topics = new List<Models.Topic>();

  var result = await _Data.GetAllTopics();

foreach (var item in result)
{
  topics.Add(new Models.Topic
  {
    Id = item.Id,
    TopicName = item.TopicName,
    VideoName= item.VideoName,
    VideoURL = item.VideoURL
  });
}

return View(topics);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 beautifulcoder
Solution 2 NeelS