I am relatively new to Web Parts and Web Forms (I have only worked a lot with the MVC framework).
I am planning to store some data in the control state. All the examples I can find put an object[] array in the control state and the base control state on the 0 index.
I don’t really like putting everything in an object[], so I wanted to create an extra class for my web part with typed properties: e.g. MyWebPartControlState. I will store the base control state in a property BaseControlState of type object.
I was wondering if this could cause any problems or if there are any other reasons why this might not be a good idea. I am wondering because it feels logical to me, but I cannot find any examples of control state where they don’t put everything in the control state directly or in a object[].
Thanks in advance.
The control state is persisted in the same field as view state and follows the same rules for serialization. All the samples you found use an object array because that’s one of the types the optimized state serializer in ASP.NET understands and for which is able to optimize serialization.
If you use a custom object the serializer won’t use the optimizations and instead will serialize your object using the
BinaryFormatterwhich will lead to bloated control state. If you want to have a strongly typed view of your state you should implementIStateManageron your custom class so that it encapsulates the transformation of itself from and to simple objects that the serializer understands.If I recall correctly the serializer can efficiently serialize the following types:
int,long, etc);DateTime;string;PairandTripletobjects containing instances of supported types.I wrote a short blogpost illustrating the differences in size resulting from a simple custom class being serialized with
BinaryFormatterversus implementingIStateManagerand decomposing to simple types that the serializer can optimize. You can find it at:ASP.NET ViewState Tips and Tricks #2