我的控制器中有一些数据(datacontracts列表)。我想在我的视图中显示该列表的字段/值。我该怎么做呢?
这是我的控制器中的代码,我获取列表数据:
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;
}
此方法返回datacontracts列表(在这种情况下只有一个)。
我在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]
有人知道如何解决这个问题吗?由于某种原因,我分配的变量是格式字符串导致此问题我假设但我该如何解决这个问题?
这是正确的方法。
模型:
public class ShipmentData
{
Task<List<ShipmentDataContract>> Get(long shipmentServiceId)
{
return YourList;
}
控制器:
public ActionResult Index()
{
var shipmentDataTest = ShipmentData.Get(//index);
return View(shipmentDataTest);
}
视图:
@Model YourShipmentModel
//here you can call Model.variable
如果要将列表用作字符串,可以发送结果
IList<string> someStrings = Get(94); // i assume than get method returns a list of "strings"
string joined = string.Join(",", someStrings );
ViewBag.shipmentTestData = joined;
现在您将列表“shipmentDataTest”作为逗号分隔列表发送到frotend。如果这是您正在寻找的,请告诉我。问候。