如何传递两个viewmodel数据给view

How to pass two viewmodel data to view

实际上,在我的例子中,它不是两个视图模型,只有一个,但我试图传递产品的单个值,然后下面的产品列表是我的控制器,因此您可以更好地理解

      public ActionResult Filter(long? id)
            {
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
//select a single product
                ProductViewModel products = new ProductViewModel();
                var pro = db.Products.Find(id);

                if (pro != null)
                {
                    products.ProductId = pro.ProductId;
                    products.ProductName = pro.ProductName;
                    products.AddDate = pro.AddDate;
                    products.ApplicationUserId = pro.ApplicationUserId;
                    products.ProductDescription = pro.ProductDescription;
                    products.ProductPictures = db.ProductPictures.Where(m => m.ProductId == id).ToList();



                }


               //Now creating list 

                ProductViewModel product = new ProductViewModel();
                var pictures = db.ProductPictures;
                var model = db.Products.Where(p=>p.ApplicationUserId==User.Identity.GetUserId()).Select(p => new ProductViewModel
                {
                    ProductId = p.ProductId,
                    ProductName = p.ProductName,
                    ProductDescription = p.ProductDescription,
                    ProductPictures = pictures.Where(x => x.ProductId == p.ProductId),
                    Category = p.Category,
                    AddDate = p.AddDate,
                    ApplicationUserId = p.ApplicationUserId,

                });


                return View(model);
            }

但是我如何将这两个值都传递给视图我尝试将单个产品的 viewbag 作为

  ViewBag.ProductId = pro.ProductId;
                    ViewBag.ProductName = pro.ProductName;
                    ViewBag.AddDate = pro.AddDate;
                    ViewBag.ApplicationUserId = pro.ApplicationUserId;
                    ViewBag.ProductDescription = pro.ProductDescription;
                    ViewBag.ProductPictures = db.ProductPictures.Where(m => m.ProductId == id).ToList();

                    ViewBag.idd = pro.ProductId;

但不知道如何在 Razor 视图中获取列表 Viewbag.productpicture 的值。使用viewbag传值是好方法还是有其他方法??

创建包含对象和对象集合属性的视图模型,例如

public CombinedProductVM
{
  public ProductViewModel Product { get; set; }
  public IEnumerable<ProductViewModel> ProductList { get; set; }
}

并在 GET 方法中,初始化一个新实例并设置属性

CombinedProductVM model = new CombinedProductVM
{
  Product = // your first query above
  ProductList = // your second query above
};
return View(model);

并在视图中使用 @model CombinedProductVM