Reputation: 70
Yesterday i was working on my asp.net mvc application where i was trying to cache some data in a field while a certain controller was in scope. The field kept clearing every time a new view got opened.
Question: Is it possible to keep your Controller in scope while you're browsing Views that are handled by said Controller?
private static List<string> _listOfStrings;
[Authorize]
public ActionResult ToView1()
{
_listOfStrings = new List<String>(){"test","test2"};
var model = new Model();
return View(model);
}
[Authorize]
public ActionResult FromView1ToView2()
{
var model = new Model(_listOfStrings);
//the issue at hand is that '_listOfStrings' is not persisted.
return View(model);
}
Anyone got an idea if this is possible? (The list is big, so i would prefer not sending it through the model into the view and vice versa)
Upvotes: 0
Views: 1425
Reputation: 415
_listOfStrings is a different variable to listOfStrings. You are not writing to or reading from the static field. In the code you have presented, _listOfStrings is not even defined.
Use one static variable and this code will work.
Upvotes: 0
Reputation: 8207
You need to read about an ASP.NET MVC lifecycle.
Short answer: no, you can't cause Controller
is destroyed after a call of an action. Detail answer: you can store (cache) data in a TempData
or in a Session
properties.
Upvotes: 3