I am creating a store with ASP.NET 4.0 MVC and C# and am fairly new to it.
I have come to creating the View page that displays the products within a certain category.
On the specific category page I want to have the product list and also want the category name with its relevant description taken from the database.
Currently the way I have done this is to have two methods in my Repository:
- Retrieve the list of products for a specific category with a string
- Retrieve the specific category with a string
I then use both these in one ActionResult and then pass them to the view.
Is there a way that I can retrieve both the product list and category name, description etc from 1 method call to the database or have i done it correctly?
Thank you for any help in advance.
My code is as follows:
StoreRepository
public class StoreRepository : topsports.Models.IStoreRepository
{
private topsportsEntities db = new topsportsEntities();
public IQueryable<Product> FindProductsByCategory(string c)
{
var products = from p in db.Products
where p.Category.Name == c
select p;
return products;
}
public Category FindCategory(string c)
{
return db.Categories.SingleOrDefault(cg => cg.Name == c);
}
}
IStoreRepository
public interface IStoreRepository
{
IQueryable<Product> FindProductsByCategory(string c);
Category FindCategory(string c);
}
StoreController
public class StoreController : Controller
{
IStoreRepository storeRepository;
public StoreController()
: this(new StoreRepository())
{
}
public StoreController(IStoreRepository repository)
{
storeRepository = repository;
}
public ActionResult Index(string c)
{
var category = storeRepository.FindCategory(c);
var products = storeRepository.FindProductsByCategory(c).ToList();
var viewModel = new StoreViewModel
{
Products = products,
Category = category
};
return View(viewModel);
}
}
StoreViewModel
public class StoreViewModel
{
public List<Product> Products { get; set; }
public Category Category { get; set; }
}
Category.aspx
<h2><%: Model.Category.Name %></h2>
<p><%: Model.Category.Description %></p>
<ul>
<% foreach (var item in Model.Products) { %>
<li>
<%: item.Name %>,
<strong><%: item.Description %></strong>
</li>
<%} %>
</ul>