I'm reading up to get a better idea of how viewstate works in asp.net webforms and have been reading this article.
One part that I don't quite understand is the Stage 5 - Raise postback event, it says that this stage does not make use of any viewstate information to raise the events (ie. TextChanged).
I thought that the viewstate would be sent back with the page on the postback and after the control tree had been populated the values from the viewstate would then be loaded in and then after that the control would interrogate the new form values comparing them against the current ones loaded from viewstate in order to tell which Changed() events it needs to raise.
If this event doesn't interact with viewstate how can it tell whether a value has changed or if it is still the same from the previous load?
Daniel, you are correct in your assumption - view state is used to determine whether a change-related event needs to be raised. That includes things like the TextChanged event on the TextBox and the SelectedIndexChanged event on the DropDownList, among others.
If you haven't read this article yet, I highly recommend it: Truly Understanding View State. It's an informative write up by Dave Reed.
Thanks!
In the case of TextChanged events, it does look at the viewstate to determine if it gets raised or not - see the answer to question 6215046:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.ontextchanged.aspx
A TextBox control must persist some values between posts to the server for this event >> to work correctly. Be sure that view state is enabled for this control.
Try enabling ViewState for TextBox.
Related
I use LoadControl method in Load event quite extensively. However I haven’t observed any problems yet, I’m afraid of what MSDN documentation says:
When you load a control into a container control, the container
raises all of the added control's events until it has caught up to the
current event. However, the added control does not catch up with
postback data processing. For an added control to participate in
postback data processing, including validation, the control must be
added in the Init event rather than in the Load event.
What does it actually mean?
Are there any other pitfalls when loading a control in the Load event?
That bit of MSDN documentation is (mostly) wrong. As you've discovered, postback data processing and validation work even if you dynamically add controls in the Load event.
Here are the stages of the ASP.NET page life cycle that are relevant to this question:
Raise the Init event.
Postbacks: Load view state and control state.
Postbacks: Load posted form data (first attempt).
Raise the Load event.
Postbacks: Load posted form data (second attempt).
Postbacks: Validate the form and raise the postback event.
The documentation is correct when it says that "the added control does not catch up with postback data processing". But it overlooks the fact that there are two attempts to load posted form data, once before the Load event and once after. Thus, if you dynamically add a control in the Load event, it will be populated with posted form data by the time the postback event (such as submitButton_Click) occurs.
As far as I can tell, here's the main difference and potential pitfall:
If you dynamically add a control in Init, you can access its posted form data in Load.
If you dynamically add a control in Load, you have to wait until the postback event (or else access the HttpRequest.Form collection directly).
It means that by the time Control_Load executes, the postback cycle has come and gone. If you have a control that needs to participate in postback, you need to load it before, so that's why the docs recommend doing it in the Init override instead.
If your controls don't participate in postback then you're OK.
I have a web page with a datagrid and a user control.
The user control has an event which the web page subscribes to.
On the user control event I need to rebind the datagrid on the web page.
I'm coming up with all sorts of problems due to extender controls that are attached to the grid indicating that they cannot be registered after prerender so it looks like the user control event occurs to late in the page life cycle. Either way those kinda errors would indicate that I'm on the wrong track completely.
I do not want a reference to my page in the user control if at all possible.
What is the best way to achieve this.
I had tried Binding the grid on PageLoad every time but found that although the Databind happened and the updated data was in the datasource that the grid contents did not reflect this. [Is it the GridView viewstate thats playing with this?]
Ding a full refresh or using a button to the page to rebind the grid allowed me to display the correct value.
Thanks in advance,
Liam
"I had tried Binding the grid on PageLoad every time but found that
although the Databind happened and the updated data was in the
datasource that the grid contents did not reflect this. [Is it the
GridView viewstate thats playing with this?]".
I think that the answer (in part at least) to this is that the third party control is using callbacks to get back to the server and not postbacks so this may be the issue. As I understand it the grid was binded OK but not rendered. [I hadn't come across the differences between Callbacks and Postbacks until this week!!]
I'm open to correction on this though. :)
Liam
I have searched the web for the answer and saw that mostly variables are saved in viewstate on page.prerender event. Then the value of the variable is set back in page load event.
However, when I save a variable in viewstate on prerender or load events, how can viewstate store the value of the variable after it is changed dynamically on codebehind?
Let's say, after page is loaded, user clicked a button which changes the value of the variable in its onClick event. Then the postback event raised since the button was clicked. According to me, the new value should have been lost and cannot be saved in the viewstate if the variable is saved in the viewstate only in prerender event. Because on postback the prerender event wont fire and the value cannot be saved.
Shouldn't I save the variable in the viewstate just before the postback event rises?
Am I wrong? If so, how can viewstate store the new value of the variable if the viewstate is saved in prerender event?
Thanks for the answer in advance..
I suspect you're confusing saving ViewState, ie. serializing the ViewState collection in memory to a string representation or to an intermediate object that can be serialized easily, with actually modifying that ViewState in-memory object with its regular accessor methods.
What you may be hearing is that the SaveViewState() method is called after PreRender event. But that has little to do with when you get to modify the contents of the ViewState collection.
Checkout points 7. Prerender the Objects and 8. ViewState Saved in the article The ASP.NET Page Life Cycle. There's a good MSDN article that touches on this as well.
(source: microsoft.com)
As per ASP.Net Page Lifecycle Overview (emphasis is mine)
PreLoad()
Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request() instance.
....
SaveStateComplete()
Raised after view state and control state have been saved for the page and for all controls. Any changes to the page or controls at this point affect rendering, but the changes will not be retrieved on the next postback.
As both Control Events and the PreRender event occur between these two, then your data should be persisted in ViewState.
Viewstate is maintained via a hidden field, so Postback has to finish before it's "set".
If you're setting it and trying to read it in the same page cycle it not going to work. You might try using the Session object, which get/sets values into memory.
I sort of answered my own question I think but I want to make sure I am understanding correctly. I initially thought that when a user provided values in a form, that on postback the values were submitted as part of the Viewstate, because TextBox.Text is part of the viewstate. Now I have found that user supplied values actually aren't applied to the controls until after the OnLoad event. This confused me because I thought that viewstate was loaded into the controls before OnLoad(or when calling Controls.Add()). I have gone over the documentation on page and control lifecycles a few times and I am just now realizing that there was a different step for handling postback data(this step didn't appear in a lot of documentation :(
1) So postback data, the values user's type into the fields, is applied after the OnLoad event, and Viewstate data is applied just before the OnLoad event?
2) So essentially all this means is that on postback the server gets two values for a TextBox.Text property, the one in Viewstate, which is like the "old" value from the previous request, and the new value supplied by the user in the form?
3) Does the .net framework apply postback data the same was as Viewstate, in that it finds the appropriate control via it's ID property? This is important because I am creating controls dynamically and I may even have forms that change structure overtime and need to think about how I handle ID's. So far I haven't been setting the ID property and everything works fine but things may be more complicated later on.
4) Does viewstate data ever get modified at all on client side? Or is the viewstate identical to what was sent by the server in the previous request(assuming no tampering)? My impression used to be that the server encoded all the control properties into the viewstate, and on the client side when the user submitted the form, the viewstate field was decoded, modified, encoded, and submitted to the server with modifications. I assumed there was a bunch of javascript doing all this for me. Now I think I had it all wrong. Instead it seems that the Viewstate never changes on client side, and all the client changes are in the postback data such that the next request the server loads viewstate, loads postback, and provides a new updated viewstate in the next response?
1) Both are loaded before Load
2) Basically, yes
3) ViewState is applied first, then Post Data
To quote Scott Mitchell(see below)
dynamically added controls must be
programmatically added to the Web page
on each and every page visit. The best
time to add these controls is during
the initialization stage of the page
life cycle, which occurs before the
load view state stage. That is, we
want to have the control hierarchy
complete before the load view state
stage arrives. For this reason, it is
best to create an event handler for
the Page class's Init event in your
code-behind class, and add your
dynamic controls there.
4) Unless you're doing something way outside of the box, ViewState is never modified client-side. "ViewState" is an HTML form field and is processed on the server side.
Here's a few images from Understanding ASP.NET View State by Scott Mitchell that may help you.
(source: microsoft.com)
(source: microsoft.com)
Bonus Reading Material: http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/Truly-Understanding-Viewstate.aspx
My impression used to be that the server encoded all the control
properties into the viewstate, and on the client side when the user
submitted the form, the viewstate field was decoded, modified,
encoded, and submitted to the server with modifications.
No, the point of the ViewState is simply to preserve the state of the page since the last "Save View State" page event, i.e. that event occurs shortly before the page is rendered to the client.
When the client makes selections to a dropdown box or changes text in a textbox the hidden ViewState property, which exists on the client page as a static HTML tag, is not dynamically changing / encoding those values, it remains the same as when the page was originally rendered.
So how is the new state of the page being preserved, i.e. how are user dropdown selections and text box values retained in ASP controls? Those dropdown selections and text box values are captured in Post Back data.
A server control can indicate that it is interested in examining the posted back data by implementing the IPostBackDataHandler interface. In this stage in the page life cycle, the Page class enumerates the posted back form fields, and searches for the corresponding server control. If it finds the control, it checks to see if the control implements the IPostBackDataHandler interface. If it does, it hands off the appropriate postback data to the server control by calling the control's LoadPostData() method. The server control would then update its state based on this postback data.
- Scott Mitchell
Is it possible to get a list of control events that are going to fire before they happen, say inside the Page_Load handler?
For example if a button was clicked can I figure this out before the button_click event handler is called?
You've picked a really tough question... the reason for this is that there are several ways that events will fire.
1) __EVENTTARGET (as mentioned above)
2) If the name of your button is MyButt, then you'll see "MyButt=" in the query string.
3) When each control (like, a TextBox for example) checks the request to see if it's value in the ViewState is different than posted, then a "Text_Changed" will fire.
But, you can use #1, and #2 to check a few places.
Unfortunately, interrogating the __EVENTTARGET value won't do the trick. Often, that value will be empty. The postback processing makes some decisions about what events to raise based on more than just the event target value (if any) testing control state values against the values posted by the form (such as for a textbox) determines whether events like TextChanged should be raised.
Aside from actually hooking up an event handler to all the controls you wish to capture events for, I don't think there is any way to determine it. It might be possible to do basically what the framework does though. You would need to do it between when the controls have been created and viewstate has been restored but before the posted values are processed. You could compare the current control values (from viewstate) with the posted values, essentially determining what events would fire.
What is your goal with this? Perhaps there is a better solution.
The following contains the mangled id for a button when clicked.
Page.Request.Form["__EVENTTARGET"]
Here is an example that I believe answers your question.
Another way would be just to set some breakpoints when debugging.