How to persist the data in memory in MVC controller?

13,097

Solution 1

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

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]);
  }

Solution 2

The instance of your controller does not persist across requests (This is why making worksheets static works, but keeping it non-static does not -- the object is only populated on a non-AJAX request due to your if statement).

One option is to populate the object no matter how the request comes in and then use the if statement to decide which item to return. The other (probably better) solution is to use the session, as Ulises mentioned.

Share:
13,097
Darf Zon
Author by

Darf Zon

Updated on June 28, 2022

Comments

  • Darf Zon
    Darf Zon almost 2 years

    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]);
        }
    

    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?

  • Darf Zon
    Darf Zon over 11 years
    Thank you Ulises, it did work out! Just one answer, it likes interesting how works Session dictionary, imagine that the brower is closed. How can I persist the Session until 60 minutes inclusive if the browser is closed.
  • Ulises
    Ulises over 11 years
    @DarfZon The default value of the Session object is 20 min (you can change this in the config file). Unless you clear it before, it will stay alive on the server side even if the user closes the browser; however, this may cause the server to assign a different session object to the user (depending on your authentication mechanism)