0

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
NeelS
  • 1
  • 1
  • Does this answer your question? [What is ViewModel in MVC?](https://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) – DubDub Feb 04 '22 at 17:15

2 Answers2

0

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.

beautifulcoder
  • 10,832
  • 3
  • 19
  • 29
  • You are right, code return JSON and that is what I am trying to consume via Razor views, but don't know how to do that . I am trying to avoid changing my controller otherwise I will have to rewrite whole WebAPI logic. – NeelS Feb 04 '22 at 19:39
  • If you need to consume JSON then you'll need to make an Ajax call from JS on the page. – beautifulcoder Feb 05 '22 at 04:21
0

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);
}
NeelS
  • 1
  • 1