views:

214

answers:

1

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.

+8  A: 

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;
        }
    }
}
Fabrizio C.
+1 for wrapping it in a custom class to centralize the key name
Andrew Hare
Thanks a lot - this was super helpful.
Jon Smock