Tuesday, November 8, 2011

Public properties in ASP.NET custom web controls ...

Came across a problem at work today ... it's related to public properties in ASP.NET custom web controls.
How and where does ASP.NET stores custom public properties in Web Forms? and how should we handle it?
The short answer is memory, thus if a post-back is done, the information will be gone.

There's 3 ways to mitigate this issue:
1) Session variable - stores the property in session ... if you need to access the property somewhere else in the session (like another page)
2) View state - stores the property in view state ... this should work if you would like to preserve the state of the page (and that you're not navigating away from the page)
3) Control state - saves the information in Control state (i think this is page of viewstate), but will still works even if viewstate is turned off. This also might be a better idea if you don't want to manually manage the view state of the variables. However, this will require more work because you will have to write your own custom ControlState methods to load/store the control state. I guess they all have its trade offs.
Here's a couple of example on how to do this:
http://aspnetresources.com/blog/how_to_preserve_control_state - great example
http://msdn.microsoft.com/en-us/library/1whwt1k7.aspx - comparison of view state v. control state

see Q&A on StackOverflow ... great answers by many by the way.
http://stackoverflow.com/questions/8057042/where-is-the-public-properties-of-a-asp-net-web-control-saved

Here's a quick update on this topic:
http://haacked.com/archive/2007/03/16/gain-control-of-your-control-state.aspx
Phil did a great great job explaining the control state and how to implement it and it works great !
The store multiple values in the control state please take a look at the comments, one of the commentator
gave a tip on how to do that.


Happy Coding!
Daniel.

No comments: