User control (ascx) and properties User control (ascx) and properties asp.net asp.net

User control (ascx) and properties


It depends. If you need to property values to be persisted beyond a post-back then you'll either have to use ViewState or Session. Since those controls are re-created on each post back you can't really maintain that state otherwise.


There's no problem at all with using ViewState to store property values for a user control.

Your statement "the more properties a user control has the more crap you'll be sticking in the ViewState" isn't necessarily true though. It's certainly possible to have ViewState track values of properties for controls but not store data in the __VIEWSTATE hidden form field variable.

Sounds crazy right? See TRULY Understanding ViewState for a brilliant article about how ViewState works.

It depends on when you initialize the properties of your controls in it's lifecycle. ViewState will only be stored in the hidden __VIEWSTATE field after the StateBag for a control starts tracking changes to property values. This happens in the OnInit method for a control which is early in the lifecycle, but there are techniques to set your property values earlier that won't incur the cost of __VIEWSTATE bloat and will still give you all the benefits.

See the linked article. It discusses everything very clearly and better than I can :-)


Your problem is exactly what ViewState is for: To persist properties of a control across postbacks, so your solution is just fine.

You could save it in session, but that really just puts the burden on the server. Depending on the number of users you have, this could get really ugly really quickly.

Also keep in mind that you have to do some housekeeping if you use session. For example, if you want to use your user control twice on the same page, you need to make sure that each control uses unique session variables.