[SOLVED] Send data from the controller to the view using DTO and API in ASP.NET MVC

Issue

I have a controller that is sending a list of items to the API and then I’m getting back the item response, it means that I’m going to receive for example if the item was not found or not valid it is working fine!! but I would like to know how can I send the dtoresponse list to a view from my controller and what I need to add in the view?

DTO

 public class ReceivedItemsRequest
    {
        public List<string> Items { get; set; }


    }
    public class ReceivedItemsResponse
    {
        public bool HasErrors { get; set; }

public List<ReceivedItemResponse> ItemResponses { get; set; } = new List<ReceivedItemResponse>() ;

    }

    public class ReceivedItemResponse
    {
        public string Barcode { get; set; }
        public string ErrorMsg { get; set; }


    }
}

Controller


       [HttpPost]
        public async Task<ActionResult> Received(List<string> itemsList)

        {
            try
            {

       var dtoRequest = new ReceivedItemsRequest();
       var dtoResponse = new ReceivedItemsResponse();

       dtoRequest.itemsList= itemsList;
dtoResponse = await API.Post<ReceivedItemsResponse, ReceivedItemsRequest>($"items/", dtoRequest);



    return View(dtoResponse);  ---> this part I'm not sure
 how to send the list and what I need to add in the view or if I need to create a view model?
            
            }

Solution

From your code, I discovered you are returning a single record not a List in the controller. So if your API return value is a single record you will send to the View like below:

Your Controller:

[HttpPost]
 public async Task<ActionResult> Received(List<string> itemsList)
 {
    ...
    dtoResponse = await API.Post<ReceivedItemsResponse, ReceivedItemsRequest>($"items/", dtoRequest);
    return View(dtoResponse);
 }

Your View:

@model Application.ReceivedItemsResponse
@{
  ViewBag.Title = "Received Items Response";
}
...HTML Code on View here...

if you are expecting a list as your dtoresponse then on your View you would have:

@model IEnumerable<Application.Models.ReceivedItemsResponse>

@{
     ViewBag.Title = "Index Item Response";
 }
 ...HTML Code Block here ....

Note that your controller does not change as long as you pass either a single record or list but your View does.

Answered By – Ngutor Tsenongo

Answer Checked By – Mary Flores (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *