I have an MVC controller and I wish to pass the same (static) information to any ActionResult in the same controller, changeable only by a new choice in the index page by the same user. I have read that it is considered bad practice to use a static variable. My sites use Windows Authentication in an Intranet environment, and up to 10 people can be looking at any one page at any time. If I understand what I read correctly, there is a danger that the static variable can be overwritten by someone other than the page user, simply by viewing the same page at the same time.
As an alternative, I read about "TempData" and "Session Variables", but so far I have not read anything indicating whether these approaches would ensure that the variable is set in the Index page by only the person viewing that instance of the page. I have pasted code samples below that show a general idea of what I mean. I have gotten them to work, my question is which method ensures that only the person viewing that instance of the page sets and reads the value?
This code sample shows use of a controller-level static variable:
public class HomeController : Controller
{
public static string _currentChoice;
public ActionResult Index(string CurrentChoice)
{
_currentChoice = string.IsNullOrEmpty(CurrentChoice)?"nothing":CurrentChoice;
ViewBag.Message = "Your choice is " + _currentChoice;
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your choice is still "+_currentChoice;
return View();
}
}
This code sample uses TempData and Session:
public class HomeController : Controller
{
public ActionResult Index(string CurrentChoice)
{
var _currentChoice = CurrentChoice;
_currentChoice = string.IsNullOrEmpty(CurrentChoice)?"nothing":CurrentChoice;
TempData["CurrentChoice"] = _currentChoice;
Session["SessionChoice"] = _currentChoice;
ViewBag.Message = "Your choice is " + _currentChoice;
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your choice is still " + TempData["CurrentChoice"]
+ "\nYour Session choice is " + Session["SessionChoice"];
return View();
}
}