问题描述
我可以设置一些单个请求的长度全局变量,让页面的所有控件可以在无需通过传递给他们每个人对此作出回应?
Can I set some kind of global variable for the length of a single Request, so that all the controls of the page can respond to it without having to pass it through to each of them?
例如,如果有人打我的母版保存按钮,可以设置我的东西让我的页面上的每个用户控件可以有一个像的Page_Load:
For instance, if someone hit a Save button on my MasterPage, could I set something so that each UserControl on my Page can have a Page_Load like:
protected void Page_Load(object sender, EventArgs e)
{
if (isSaving) // isSaving is a global variable
{
saveData(); // save myself
}
loadData();
}
这似乎只是比有从母版的委托调用页面的保存功能,然后调用UC1.saveData()为每个用户控件方便很多,虽然我知道这是更好的面向对象的思想。
It just seems a lot easier than having a delegate from the masterpage call the Page's save function, which then calls UC1.saveData() to each UserControl, though I know that's better Object Oriented thinking.
推荐答案
是的,你可以。看明显的地方:HttpContext的和 HttpContext.Current.Items
的集合,是始终在请求处理访问(见http://msdn.microsoft.com/en-us/library/system.web.httpcontext.items.aspx).
Yes, you can. Look at the obvious place: the HttpContext and the HttpContext.Current.Items
collection that is always accessible during request handling (see http://msdn.microsoft.com/en-us/library/system.web.httpcontext.items.aspx).
正如一个的提示的:
public static class RequestScopedData
{
private const string key = "key_that_you_choose";
public static bool IsSaving
{
get
{
object o = HttpContext.Current.Items[key];
return Convert.ToBoolean(o);
}
set
{
HttpContext.Current.Items[key] = value;
}
}
}
这篇关于对于请求的时间设置全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!