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?
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();
}
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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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).
Just as an hint:
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;
}
}
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0