【发布时间】:2019-04-03 16:04:19
【问题描述】:
我有一个索引操作,可以从数据库中加载我的所有产品。我已验证有产品被拉出并将它们发送到视图。
唯一的问题是当视图加载时它说表中没有数据条目?
控制器
public class InventoryController : Controller
{
private readonly IRepository<Product> _productContext;
public InventoryController(IRepository<Product> productContext)
{
_productContext = productContext;
}
// GET: Inventory
public ActionResult Index()
{
List<Product> Products = _productContext.Collection().ToList();
return View(Products);
}
}
使用脚本查看
@model IEnumerable<SuperStockpile.Core.Models.Product>
@{
ViewBag.Title = "Inventory";
}
<h2>Inventory</h2>
<p>
@Html.ActionLink("Add New Product","Create","Inventory",null,new {@class = "btn btn-primary"})
</p>
<table class="table table-hover table-bordered" id="products">
<thead>
<tr>
<th>@Html.DisplayNameFor(model => model.UPC)</th>
<th>@Html.DisplayNameFor(model => model.SKU)</th>
<th>@Html.DisplayNameFor(model => model.Cost)</th>
<th>@Html.DisplayNameFor(model => model.DiscountPercent)</th>
<th>@Html.DisplayNameFor(model => model.ItemCode)</th>
<th>@Html.DisplayNameFor(model => model.CreatedAt)</th>
</tr>
</thead>
<tbody></tbody>
</table>
@section scripts
{
<script>
$(document).ready(function() {
$('#products').DataTable();
});
</script>
}
我真的不确定我做错了什么。数据表按预期显示在视图中。好像数据没有进入我的视野?
任何帮助或建议将不胜感激。
【问题讨论】:
-
我首先将
@model IEnumerable<SuperStockpile.Core.Models.Product>更改为@model List<SuperStockpile.Core.Models.Product>。对我来说,有时会以奇怪的方式迭代 IEnumerable 中断。 -
当我这样做时,我失去了对所有产品属性的访问权限,并且网页出现了错误。
-
这没有任何意义。你是
@using System.Collections.Generic吗?您将List<>返回到视图,因此视图自然应该在顶部有@model List<>。通过将List<>返回到视图中,仅将其解释为视图中的@model IEnumerable<>,您将失去List类的一些功能 -
是的,我正在使用它。是的,我将@model List 放在了顶部,它说该模型没有名为 UPC 的属性。
-
因为这个
@Html.DisplayNameFor(model => model.UPC)试图访问List对象上的属性UPC,而不是List中的项目。您需要将所有@Html.DisplayNameFor放在 foreach 循环中,并在该 foreach 循环中使用@Html.DisplayNameFor(model => m.UPC)执行foreach (var m in Model)
标签: javascript c# asp.net asp.net-mvc datatables