ASP.NET MVC 5通过viewdata 向视图传递多个对象

本文介绍了如何在ASP.NET MVC 5中利用ViewData组件有效地将多个对象从控制器传递到视图。通过实例展示了查询数据并在cshtml文件中进行迭代显示的方法。
摘要由CSDN通过智能技术生成

在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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值