Search code examples
c#listvue.jsmodel-view-controllerdatacontract

How do I pass a list of objects from controller to view?


I have some data (a list of datacontracts) in my controller. I want to show the fields/ values of that list inside my view. How do I do this properly?

This is the code inside my controller where I get the list data:

public List<ShipmentDataContract> Get(long shipmentServiceId)
        {
            Logging.Instance.Info($"Shipment request came in for shipment with ShipmentServiceId = {shipmentServiceId}");
            ShipmentQueryResult shipmentQueryResult = GetShipmentByShipmentServiceIdResult(shipmentServiceId);
            Logging.Instance.Debug($"Shipment queried with ShipmentServiceId = {shipmentServiceId}");
            List<ShipmentDataContract> shipmentDataContracts = GetShipmentsFromResult(shipmentQueryResult);
            Logging.Instance.Info($"Shipment retrieved for shipment with ShipmentServiceId = {shipmentServiceId}.");
            return shipmentDataContracts;
        }

This method returns a list of datacontracts (only one in this case).

I made a test method inside the same controller as well within the Index method:

public ActionResult Index()
        {
            var shipmentDataTest = Get(94);

            ViewBag.shipmentTestData = shipmentDataTest;

            return View();
        }

When I debug the backend, it returns the right shipment (with ID 94).

Now I want to show the shipment information within my view.

I made a variabele in my view:

<script>
    var shipmentTestData = '@ViewBag.shipmentTestData';
</script>

And within my Vue app file assigned the right values:

var Vue = new Vue({
    el: "#vueapp",
    components: ["error"],
    data: {
        shipmentTestData: shipmentTestData
    }
});

Than when I call the data, it will not show the values, but a generic string.

<p>{{ shipmentTestData }}</p>

It returns this:

System.Collections.Generic.List`1[ShipmentDataContract]

Does someone know how to get this fixed? For some reason the variable that I assign is of format string which causes this issue I assume but how can I fix this?


Solution

  • This is the proper way.

    Model:

       public class ShipmentData
       {
           Task<List<ShipmentDataContract>> Get(long shipmentServiceId)
           {
              return YourList;
           }
    

    Controller:

      public ActionResult Index()
        {
            var shipmentDataTest = ShipmentData.Get(//index);
    
            return View(shipmentDataTest);
        }
    

    View:

        @Model YourShipmentModel
        //here you can call Model.variable