我是新来的asp.net mvc,viewmodels对我来说也是新手。我有一个显示产品的视图。在视图中,我想以一格显示所有产品。 然后在另一个div中,我只想显示featuredProducts,并在另一个div中显示Toprated。我正尝试为每个视图模型使用不同的视图模型,因为我将在不同的页面上再次使用这些视图模型。这是做这件事的正确方法,如果不是这样的话。另外我怎样才能用viewmodels来做这个练习。View中的多个ViewModels asp.net MVC
域模型
public class Product
{
public int ProductId { get; set; }
public string SKU { get; set; }
public string Name { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public Boolean FeaturedProduct { get; set; }
public Boolean NewProduct { get; set; }
public Boolean TopRated { get; set; }
public Boolean BestSellers { get; set; }
}
ViewModelProductsMain(父)
public class ViewModelProductsMain
{
public ViewModelProducts Products{ get; set; }
public ViewModelTopRated TopRated{ get; set; }
public ViewModelFeatured Featured{ get; set; }
}
的ViewModels(儿童)
public class ViewModelProducts (Child)
//all products
{
public int ProductId { get; set; }
public string SKU { get; set; }
public string Name { get; set; }
public string Title { get; set; }
public string Description { get; set; }
}
public class ViewModelTopRated (Child)
//all products with TopRated true
{
public int ProductId { get; set; }
public string SKU { get; set; }
public string Name { get; set; }
public string Title { get; set; }
public string Description { get; set; }
}
public class ViewModelFeatured (Child)
//all products with Featured true
{
public int ProductId { get; set; }
public string SKU { get; set; }
public string Name { get; set; }
public string Title { get; set; }
public string Description { get; set; }
}
控制器
public ActionResult Index()
{
//How do I, instantiate and populate the model
var model = new ViewModelProductsMain();
return View(model);
}
查看
@model IEnumerable<myProject.ViewModels.ViewModelProductsMain >
没有兄弟所有模型中包含相同的属性 –
的单一模式可以使名为'ProductsViewModel'这项工作 –
一个视图模型,然后你的'ViewModelProductsMain'但我怀疑你真的想'公开IEnumerable Products {get;组; }'因为它的一个集合(也许精选也是如此?) –