[英]Is it better to use TempData, Session, or a static variable to share the same value between ActionResults in the same controller?
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. 我有一个MVC控制器,我希望将相同的(静态)信息传递给同一控制器中的任何ActionResult,只能由同一用户在索引页面中的新选项进行更改。 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.
我的网站在Intranet环境中使用Windows身份验证,任何时候最多可以有10个人查看任何一个页面。 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. 作为替代方案,我读到了“TempData”和“Session Variables”,但到目前为止,我还没有看到任何指示这些方法是否能确保变量在Index页面中仅由查看该页面实例的人设置的内容。 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 : 此代码示例使用TempData和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();
}
}
You'll want to use the Session. 你会想要使用Session。 Each of the options you presented have different use cases:
您提供的每个选项都有不同的用例:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.