Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to persist the data in memory in MVC controller?

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?

like image 828
Darf Zon Avatar asked Jan 02 '13 19:01

Darf Zon


People also ask

How do you persist data between consecutive request in MVC?

TempData is used to pass data from current request to subsequent request (i.e., redirecting from one page to another). Its life is too short and lies only till the target view is fully loaded. But you can persist data in TempData by calling the method Keep () .

How do you persist data in TempData?

stringstr = TempData["MyData"]; Even if you are displaying, it's a normal read like the code below: @TempData["MyData"]; Condition 3 (Read and Keep): If you read the “TempData” and call the “Keep” method, it will be persisted. @TempData["MyData"]; TempData.

How do you maintain state in MVC?

In ASP . NET MVC, ViewData, View Bag, TempData is used to maintain the state in our page/view. Viewdata, ViewBag is used to transfer date/information from controller to view in the current request. TempData use to transfer data from controller to another controller.


1 Answers

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]);
  }
like image 120
Ulises Avatar answered Nov 06 '22 06:11

Ulises