在controller查询到的数据是:
public ActionResult Index()
{
var products = GetTopSellingProducts(1);
var genres = storeDB.Genres.ToList();
ViewData["IndexProducts"] = products;
ViewData["IndexGenres"] = genres;
return View();
}在一般的viewtag中,只能传递一个对象,此时可以使用viewdata
cshtml迭代代码如下:
@foreach (var product in ViewData["IndexProducts"] as List<Product>)
{
<li class="col-lg-2 col-md-2 col-sm-2 col-xs-4 container">
<a href="@Url.Action("Details", "Store", new { id = product.ProductId })">
<img alt="@product.ProductName" src="@Url.Content(@product.ProductImgUrl)" />
<h4>@product.ProductName</h4>
</a>
</li>
}如果提示某个model类不在命名空间,那么就在view文件夹下的web.config中加入namespace

本文介绍了如何在ASP.NET MVC 5中利用ViewData组件有效地将多个对象从控制器传递到视图。通过实例展示了查询数据并在cshtml文件中进行迭代显示的方法。
最低0.47元/天 解锁文章
320

被折叠的 条评论
为什么被折叠?



