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?
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 () .
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.
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.
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]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With