我有一个下拉菜单,当您选择一个选项值时,请提交表单,并避免重复的数据库调用,我将非敏感对象存储在会话中。
private List<Employee> stafflist
{
get { return Session["stafflist"] as List<Employee>; }
set { Session["stafflist"] = new Employee(); }
}
private void RemoveStaff()
{
Session.Remove("stafflist");
}
但是在我的
[HttpPost]
public ActionResult index (...)
{
//why can't I get the list of staff like this?
ViewBag.staff=stafflist.Where(..).toList();
//is the below still needed? i thought i
//have a session variable declare above,
//and to avoid 30x repetitive db calls?
//also note when i include the below the code runs fine,
//however, if i take it out it doesn't. i would like to avoid repetitive db calls
stafflist=db.Employee.toList();
}
首先,您不应该阻止查询数据库。正确的缓存很难正确实现,并且数据库完全能够执行查询和缓存数据。
如果您绝对确定要绕过数据库,并查询客户端(即在控制器中),则需要从数据库中至少每个访问者一次提取整个人员列表。
您可以在对该控制器的第一个GET调用中执行此操作,假设用户将始终访问该控件:
[HttpGet]
public ActionResult Index (...)
{
var cachedStaff = db.Employee.toList();
Session["stafflist"] = cachedStaff;
}
然后在POST中,您实际上要执行数据库查询(同样,考虑让数据库执行其擅长的工作),您可以从会话中查询列表:
[HttpPost]
public ActionResult Index (...)
{
var cachedStaff = Session["stafflist"] as List<Employee>();
// TODO: check cachedStaff for null, for when someone posts after
// their session expires or didn't visit the Index page first.
var selectedStaff = cachedStaff.Where(..).ToList();
// the rest of your code
}
然后,您引入的属性可以用作语法糖来稍微清理一下代码:
private List<Employee> CachedStaff
{
get { return Session["stafflist"] as List<Employee>; }
set { Session["stafflist"] = value; }
}
[HttpGet]
public ActionResult Index (...)
{
CachedStaff = db.Employee.toList();
}
[HttpPost]
public ActionResult Index (...)
{
// TODO: this will throw an ArgumentNullException when
// the staff list is not cached, see above.
var selectedStaff = CachedStaff.Where(..).ToList();
// the rest of your code
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句