我正在尝试使用 MVC3 实现结果过滤器并遇到这样的问题:
public ActionResult Index(int? SubID)
{
var product = db.Product.Where(s => s.SubID == SubID).Include(t => t.SubCategory);
if (SubID.HasValue)
{
ViewBag.SubID = new SelectList(db.SubCategory, "SubID", "SubNameVN", SubID);
}
else
{
ViewBag.SubID = new SelectList(db.SubCategory, "SubID", "SubNameVN");
}
return View(product);
}
上面的这个工作正常,但下面的总是给我整个表的结果,不管我把它放在什么条件下:
public ActionResult Index(int? SubID)
{
var product = db.Product.Include(t => t.SubCategory);
if (SubID.HasValue)
{
ViewBag.SubID = new SelectList(db.SubCategory, "SubID", "SubNameVN", SubID);
product.Where(s => s.SubID == SubID);
}
else
{
ViewBag.SubID = new SelectList(db.SubCategory, "SubID", "SubNameVN");
}
return View(product);
}
甚至这个也不起作用:
public ActionResult Index(int? SubID)
{
var product = from m in db.Product
select m;
if (SubID.HasValue)
{
ViewBag.SubID = new SelectList(db.SubCategory, "SubID", "SubNameVN", SubID);
product.Where(s => s.SubID == SubID);
}
else
{
ViewBag.SubID = new SelectList(db.SubCategory, "SubID", "SubNameVN");
}
product.Include(t => t.SubCategory);
return View(product);
}
所以请告诉我这 3 种方法有什么区别,请向我解释为什么 #2 和 #3 不起作用?