Link to home
Start Free TrialLog in
Avatar of SamCash
SamCashFlag for United States of America

asked on

ASP Best practice to save var in ViewState

I have a var that is altered by several processes dependent on the users actions.  Is there a place where I can save this variable at the last pico second :-), just before page unloads, or after everything has finished changing.  I tried OnSaveStateComplete but it is too late.  Is there a correct event I c an use, or something?

Thanks
Sam
Avatar of Jaydev Rathod
Jaydev Rathod

You can store in ViewState or Session variable depend on your requirement.
ViewState is available for entire page and Session for application
Avatar of SamCash

ASKER

Jaydev,

Thanks for the response.

Further clarification...

ViewState["MyClass"] = MyClass;
Where may I put this one line of code so I am assured it will be its last state?

I do not want to put it everywhere on the page (Code Behind) that it might be accessed, there should be a place (Event) during the life cycle it could be put so it is after all changes are final.

I "think" it should be in Page_PreRender, it seems to work, but I cannot find anything (Google) on point, scarry.

-- side issue
I had quite an issue getting Page_PreRender to fire, found two posts
 1) this.PreRender += new System.EventHandler(this.Page_PreRender);
     private void Page_PreRender(object sender, EventArgs e){...}

2) protected override void OnPreRender(EventArgs e) {...}

in attempting to figure out what I may be doing with "override" I deleted it, and everything still worked!
3) protected void OnPreRender(EventArgs e)

Which should I use 1, 2, 3, or something else?
Is Page PreRender the best practice to add a variable to ViewState?

Kind Regards
Sam
Avatar of SamCash

ASKER

Update, #3 did not work, "override" is required, sorry.
ASKER CERTIFIED SOLUTION
Avatar of Mlanda T
Mlanda T
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of SamCash

ASKER

MlandaT,

Thanks for sharing your experience!

Best Regards
Sam