如何将对象列表从控制器传递给视图?

我的控制器中有一些数据(数据合同列表)。我想在我的视图中显示该列表的字段/值。我该如何正确地做到这一点?


这是我的控制器中获取列表数据的代码:


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;

        }

此方法返回数据合同列表(在本例中只有一个)。


我在同一个控制器内以及 Index 方法内创建了一个测试方法:


public ActionResult Index()

        {

            var shipmentDataTest = Get(94);


            ViewBag.shipmentTestData = shipmentDataTest;


            return View();

        }

当我调试后端时,它返回正确的装运(ID 为 94)。


现在我想在我的视图中显示装运信息。


在我看来,我做了一个变量:


<script>

    var shipmentTestData = '@ViewBag.shipmentTestData';

</script>

在我的 Vue 应用程序文件中分配了正确的值:


var Vue = new Vue({

    el: "#vueapp",

    components: ["error"],

    data: {

        shipmentTestData: shipmentTestData

    }

});

比起我调用数据时,它不会显示值,而是显示通用字符串。


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

它返回这个:


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

有人知道如何解决这个问题吗?出于某种原因,我分配的变量是格式字符串,这导致了我假设的这个问题,但我该如何解决这个问题?


holdtom
浏览 119回答 2
2回答

小怪兽爱吃肉

这是正确的方法。模型:&nbsp; &nbsp;public class ShipmentData&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp;Task<List<ShipmentDataContract>> Get(long shipmentServiceId)&nbsp; &nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return YourList;&nbsp; &nbsp; &nbsp; &nbsp;}控制器:&nbsp; public ActionResult Index()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var shipmentDataTest = ShipmentData.Get(//index);&nbsp; &nbsp; &nbsp; &nbsp; return View(shipmentDataTest);&nbsp; &nbsp; }看法:&nbsp; &nbsp; @Model YourShipmentModel&nbsp; &nbsp; //here you can call Model.variable

Smart猫小萌

如果您想将列表用作字符串,您可以发送结果&nbsp;IList<string> someStrings = Get(94); // i assume than get method returns a list of "strings"&nbsp;string joined = string.Join(",", someStrings );&nbsp;ViewBag.shipmentTestData = joined;现在您要将列表“shipmentDataTest”作为逗号分隔列表发送给前端。让我知道这是否是您要找的东西。问候。
打开App,查看更多内容
随时随地看视频慕课网APP