views:

139

answers:

2

I have implemented a user control that I reuse on several pages. However, I have run into variety of issues such as session maintenance across pages, session clearing on navigating away - essentially control state maintenance, that I am wondering that all this is worth the headache.

Every time the page is loaded, a control is added to it, I use session to re-create its state, where applicable. When I navigate away from a page, I clear the session through javascript window.onunload with the web method. Window.onunload has been giving me trouble by executing AFTER the new page_load event hence creating a situation that is very difficult to deal with.

Any tips on how to fix this w/o giving up on user controls all together? What is the other way to re-use code w/o ripping one's hair out? Thanks!

+1  A: 

This is a common headache. Based on all the literature I've seen, as well as my own personal experience, it's just not practical to depend on the clearing session through javascript or any other means. The concept of Session state is overlaid on HTTP; it was never intended to be session-aware.

It sounds like you are stressing Session state to its breaking point. Have you considered ViewState or a database for managing stateful data? Why is it critical to clear the session data every time the user navigates away?

Dave Swersky
If the user clicks on the top level menu, they should get the default control state, not the previously remembered state....hence in certain places, I would like to clear session.
gnomixa
ViewState is a better solution.
Steven A. Lowe
ViewState is a dictionary that can hold serializable objects and is persisted across postbacks in a Base64-encoded string in a hidden form field. It can be useful for state management across postbacks but can increase the amount of data going over the wire.Usage: ViewState["MyData"] = myObj;
Dave Swersky
^ i actually can't have too much data going over the wire, but in this particular case it's the same case with Session object as well - it's also stored on the server.
gnomixa
+1  A: 

I solved the problem with IsPostBack usage on the page that hosts the user control. That way every time the page is not a result of postback, the state variables of the user control will be initialized.

gnomixa