I have a Page (form) that has many UserControls on it, and I'm trying to have a single button to save everything. The UserControls are actually nested, so I wanted to somehow signal to each UC that it should save itself, instead of somehow wrapping everything into one event or having a single event trigger a cascade of save events.
My plan was to use a static class (props to this answer for the code):
public static class RequestScopedFormData
{
private const string save_key = "request_form_is_saving";
public static bool FormIsSaving
{
get
{
object o = HttpContext.Current.Items[save_key];
return Convert.ToBoolean(o);
}
set
{
HttpContext.Current.Items[save_key] = value;
}
}
}
Ideally a button on my MasterPage would set RequestScopedFormData.FormIsSaving = true, and as .NET builds the Page and its UserControls, they would know to perform a save on themselves.
The problem I'm having is that I can't get an event to fire early enough in the Page lifecycle to save the UserControls. Even if I move the saving code to the PreRender event, and I move the save ImageButton to the Page itself (instead of the MasterPage), I cannot get the FormIsSaving set to true before the UC saving check.
It happens something like this:
So unfortunately the SaveButton_Click method happens AFTER the UCs are loaded, so they never save.
You can also check if postback was caused by the save button:
Request.Form["__EVENTTARGET"].Contains({YourSaveButton}.UniqueID)
The form variables are available earlier in the page life cycle.