我正在用ASP.NET 4.0 MVC和C#創建一個商店,而且對它來說相當新穎。從我的存儲庫中運行2個方法的ActionResult是否正確?
我已經開始創建顯示某個類別內的產品的View頁面。
在特定的分類頁面上我想要產品列表,並且還希望分類名稱及其從數據庫中取得的相關描述。
目前,我已經做到了這一點的辦法是在我的庫兩種方法:
- 檢索的產品列表與字符串特定類別
- 用字符串檢索特定類別
然後我在一個ActionResult中使用這兩個,然後將它們傳遞給視圖。
有沒有一種方法可以從1方法調用數據庫中檢索產品列表和類別名稱,描述等等,或者我是否可以正確地完成它?
感謝您提前提供任何幫助。
我的代碼如下:
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>
感謝您對我的問題的詳細回覆,爲我解決了一些問題。 – user485168 2010-10-24 09:14:30