在我的Web应用程序中,我想在视图中显示由Category_ID分隔的项目列表。
要做到这一点在我创建的视图模型中
public class ProductsViewModel
{
public IEnumerable<CakesViewModel> CakesVM { get; set; }
public IEnumerable<PizzaViewModel> PizzaVM { get; set; }
public IEnumerable<FastFoodsViewModel> FastFoodsVM { get; set; }
}
在控制器中:
public ActionResult Index()
{
List<Products> Cakes = db.Products.Where(x=>x.Category_ID == 1).ToList<Products>();
List<Products> Pizzas = db.Products.Where(x => x.Category_ID == 2).ToList<Products>();
List<Products> FastFoods = db.Products.Where(x => x.Category_ID == 3).ToList<Products>();
List<ProductsViewModel> allProducts = new List<ProductsViewModel>();
foreach (Products item in Cakes)
{
CakesViewModel productsView = new CakesViewModel();
productsView.ID = item.ID;
productsView.ProductPrice = item.ProductPrice;
productsView.ProductName = item.ProductName;
productsView.Is_Customizable = item.Is_Customizable;
productsView.Category_Name = item.FoodCategories.CategoryName;
productsView.ProductPicture = item.ProductPicture;
allProducts.Add(productsView);
}
foreach (Products item in Pizzas)
{
PizzaViewModel productsView = new PizzaViewModel();
productsView.ID = item.ID;
productsView.ProductPrice = item.ProductPrice;
productsView.ProductName = item.ProductName;
productsView.Is_Customizable = item.Is_Customizable;
productsView.Category_Name = item.FoodCategories.CategoryName;
productsView.ProductPicture = item.ProductPicture;
allProducts.Add(productsView);
}
foreach (Products item in FastFoods)
{
FastFoodsViewModel productsView = new FastFoodsViewModel();
productsView.ID = item.ID;
productsView.ProductPrice = item.ProductPrice;
productsView.ProductName = item.ProductName;
productsView.Is_Customizable = item.Is_Customizable;
productsView.Category_Name = item.FoodCategories.CategoryName;
productsView.ProductPicture = item.ProductPicture;
allProducts.Add(productsView);
}
return View(allProducts);
}
我想知道这里不能添加项目
allProducts.Add(productsView);
想知道如何将Cakes
列表添加到CakesViewModel ,
Pizza to
PizzaViewModel``并传递到视图。
1条答案
按热度按时间kmpatx3s1#
1.您的
allProducts
变量不应该是List<ProductsViewModel>
类型,它应该是像下面这样的简单对象ProductsViewModel allProducts = new ProductsViewModel(){
CakesVM =new List<CakesViewModel>()
,PizzaVM =new List<PizzaViewModel>(),
FastFoodsVM =new List<FastFoodsViewModel>(),
};
1.您应该在每个
foreach
循环中向各自的List添加单个项,如下所示foreach (Products item in Cakes)
1.在所有三个
foreach
循环中执行相应的操作。