将对象存储在会话变量中

空值

我有一个下拉菜单,当您选择一个选项值时,请提交表单,并避免重复的数据库调用,我将非敏感对象存储在会话中。

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(); 
}
CodeCaster

首先,您不应该阻止查询数据库。正确的缓存很难正确实现,并且数据库完全能够执行查询和缓存数据。

如果您绝对确定要绕过数据库,并查询客户端(即在控制器中),则需要从数据库中至少每个访问者一次提取整个人员列表。

您可以在对该控制器的第一个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] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

将对对象属性的引用存储在变量中

来自分类Dev

将对对象属性的引用存储在变量中

来自分类Dev

在会话中存储对象

来自分类Dev

将对象存储在会话中后,当对象更改时,它将在会话中自动更新。为什么?

来自分类Dev

将对象存储在localStorage中

来自分类Dev

狂欢-在会话中存储对象

来自分类Dev

在 PHP 会话中存储对象

来自分类Dev

如何在MeteorJS / React中将对象存储在变量中以稍后返回?

来自分类Dev

将对象附加到本地存储中

来自分类Dev

如何将对象存储在向量中?

来自分类Dev

将对象存储到数组中-Java

来自分类Dev

将对象附加到本地存储中

来自分类Dev

将对对象的引用存储在ArrayList中

来自分类Dev

如何将对象存储在向量中?

来自分类Dev

将对象数组存储到SQLite中?

来自分类Dev

将对象字段与javascript中的变量连接

来自分类Dev

将对象中的位置作为变量传递

来自分类Dev

将对象字段与javascript中的变量连接

来自分类Dev

在会话数组中存储不同的post变量

来自分类Dev

如何在会话中存储变量?

来自分类Dev

将php exec存储在会话变量中

来自分类Dev

将密钥存储在会话变量中

来自分类Dev

如何在整个会话中存储变量?

来自分类Dev

在javascript中设置会话变量或本地存储

来自分类Dev

将增值存储在会话变量中并打印

来自分类Dev

如何访问会话中存储的动态对象

来自分类Dev

获取存储在jsp会话中的对象的属性

来自分类Dev

PHP-将会话链接的名称存储在会话变量中

来自分类Dev

PHP-将会话链接的名称存储在会话变量中