实际上它不是两个viewmodel在我的情况下只有一个,但我试图传递单个产品值,然后下面的产品列表是我的控制器,所以你可以更好地理解
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.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;
但不知道如何在剃刀视图中获取列表Viewbag.productpicture的价值。是使用viewbag传递值的好方法还是有其他方法?
答案 0 :(得分:1)
创建一个视图模型,其中包含对象和对象集合的属性,例如
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