如何坚持MVC控制器,内存中的数据? [英] How to persist the data in memory in MVC controller?

查看:83
本文介绍了如何坚持MVC控制器,内存中的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请看看下面的动作。当用户导航的第一次,创建一个对象,然后当他在页面,访问导航再次动作,而是通过Ajax请求和数据disappers(工作表=空)。

Please look at the below action. When the user navigate the first time, creates a object, then while he navigates in the page, access again to the Action but through Ajax request and the data disappers (worksheets = null).

    private static List<Worksheet> worksheets;
    public ActionResult DoTest()
    {
        if (Request.IsAjaxRequest())
        {
            return PartialView("_Problems", worksheets[1]);
        }

        // first time
        worksheets = new List<Worksheet>()
        {
            new Worksheet("Hoja 1", ...),
            new Worksheet("Hoja 2", ...)
        };
        return View(worksheets[0]);
    }

我的第一个溶液的变量工作表设置为静态的,但我认为这不是一个很好的做法。我做一个好办法,还是有其他tweeks?

My first solution was set the variable worksheets to static, but I supposed this is not a good practice. Am I doing a good way or are there another tweeks?

推荐答案

这静态变量远点,特别是如果数据是依赖于用户的。你可以利用 ASP.NET对话的对象。

Stay away from static variables, especially if the data is user-dependent. You could take advantage of the ASP.NET Session object.

这可以很容易地在你的情况下,通过改变工作表字段存储其在Session对象中值的属性完成的。这样一来,这将可在后续调用。例如:

This can be easily done in your case by changing your worksheets field to a property that stores its value in the Session object. This way, it will be available on subsequent calls. Example:

  private List<Worksheet> worksheets
  {
    get{ return Session["worksheets"] as List<Worksheet>;}
    set{ Session["worksheets"] = value; }
  }

  public ActionResult DoTest()
  {
      if (Request.IsAjaxRequest())
      {
        return PartialView("_Problems", worksheets[1]);
      }

      // first time
      worksheets = new List<Worksheet>()
      {
          new Worksheet("Hoja 1", ...),
          new Worksheet("Hoja 2", ...)
      };
      return View(worksheets[0]);
  }

这篇关于如何坚持MVC控制器,内存中的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆