I am developing an ASP.NET MVC 3 web application using Razor and C#.
I just discovered that I have some problems with global variables, probably because I am relatively new to MVC.
I have a controller with some global variables and action methods. I declared a global variable in order to allow the action methods to manipulate it and reflect the manipulations to all the action methods. I have the following situation:
public class myController : Controller
{
private string _MyGlobalVariable;
public ActionResult Index()
{
_MyGlobalVariable = "Hello";
//other code
return View("MyView");
}
public ActionResult Print()
{
_MyGlobalVariable += "Print";
return View("PrintView", _MyGlobalVariable);
}
}
The Print() action method is called with an Html.ActionLink() from the MyView View.
The surprising thing is that the value of _MyGlobalVariable is not kept! So the value of _MyGlobalVariable before the instruction _MyGlobalVariable += "Print" is equal to null.
Am I making some mistake? How can I keep the value of global variables between calls to Views?
Thanks
Francesco
PS: in my specific case the global variable is a Dictionary<K,V> but I guess it does not change the logic.
PPS: I know you can use ViewModels instead of global variables to pass data between action methods but in my case is much less code if I use a Dictionary<K,V> which usually I don't wrap in ViewModels (I use POCOs or Lists<T>)