I have a view which displays products and the corresponding’s category details in my application. It’s inheriting from a viewmodel in order to fetch both products and category info that I need to display.
public ViewResult Index(string id, int page = 1, int pagesize = 10)
{
var viewModel = new PagedProductList()
{
CurrentPageIndex = page,
PageSize = pagesize
};
viewModel.category = db.Category.First(c => c.Id == id);
viewModel.products = db.Product
.Where(i => i.Category.Id == viewModel.category.Id)
.OrderBy(i => i.Id)
.Skip((viewModel.CurrentPageIndex - 1) * viewModel.PageSize)
.Take(viewModel.PageSize)
.Include(p => p.ProductAttributeValues);
return View(viewModel);
}
As you can see I’m passing the viewmodel's category id to the viewmodel’s products where clause.
Question 1: Would this work better in terms of performance or some other way if I moved the products code in a separate child action and then call the action from the parent view using Html.Action passing the category model id from the parent.
Question 2: Is there any other better way to fetch both the category info and the corresponding products. I can’t use something like db.Category.Include(“Products”) because I won’t be able to do paging on the products.