I have troubles managing data fetched by users on my app.
So far, if my understanding of ASP.NET MVC is what I think it is, I cannot put fetched data in static fields. For example, it would be a bad idea to do this:
private static List<MyObjects> listObjects = new List<MyObjects> { get; set;}
public List<MyObjects> GetMyObjects (int _objectID)
{
using(MyDatabase database = new MyDatabase())
{
listObjects = (from o in database.MyObjects
where o.MatchingID == _objectID
select o).ToList();
return listObjects;
}
}
Because that would make the list of data available to all users on the web site. So I've read a few things and I thought that I needed to put things into MVC Session
dictionary so that each user would browse through their own lists.
So I have these methods:
public List<MyObjects> GetMyObjects (int _objectID)
{
using(MyDatabase database = new MyDatabase())
{
List<MyObjects> listObjects = (from o in database.MyObjects
where o.MatchingID == _objectID
select o).ToList();
return listObjects;
}
}
[HttpGet]
public ActionResult SeeItemsByID(int? _objectID)
{
// Pre-validations to make sure that the ID is valid, then:
List<MyObjects> listObjects = GetMyObjects((int)_objectID);
Session["myObjects"] = listObjects;
return RedirectToAction("SeeItems");
}
[HttpGet]
public ActionResult SeeItems()
{
List<MyObjects> listObjects = Session["myObjects"] as List<MyObjects>;
if(listObjects == null)
{
return RedirectToAction("Home");
}
return View(listObjects);
}
[HttpGet]
public ActionResult SeeItemsCompact()
{
List<MyObjects> listObjects = Session["myObjects"] as List<MyObjects>;
if(listObjects == null)
{
return RedirectToAction("Home");
}
return View(listObjects);
}
So let's resume the process:
First the user clicks on a link which calls the SeeItemsByID
action, then it is redirected to the SeeItems
action. In this view the user may click on a link to see the result "compacted" for any reasons. However, in my app, when the SeeItemsCompact
method is called right after, all the Session data is lost.
How? And how could I keep this data alive?