Why use a ViewState-backed Property?
This is the first post in a multi-part series on using ViewState to back your Page Properties. If you’ve done any kind of development with ASP.NET then you’ve probably had to use a ViewState-backed Property at some point. Accessing and setting a Property is much easier than working with ViewState directly throughout your code, especially if the name of your Key may change. There is one thing to consider, though.
Default Value for a ViewState-backed Property
It’s generally good practice to check your ViewState-backed Property for null before trying to access it. One thing worth noting is that you may want to display a default value if one hasn’t been set. The following code may look familiar:
Null Coalescing Operator
Lately there have been quite a few blog posts on using the null coalescing operator (??). I won’t go into detail here about its use except to say that it returns the first operand if it is not null and the second operand if the first is null. When applied to ViewState-backed Properties the code can be shortened and, in my opinion, made more readable. Consider the following code which essentially works the same as the previous example:
If ViewState["MyDefaultValue"] is null then the string "My default value" is returned. If it is not null then the value it holds is cast to a string and returned. In the past, developers have argued that the null coalescing operator makes code more difficult to read. With all the attention it’s gotten lately, I no longer think that’s a valid argument. In fact, I’ll be using it throughout this series on ViewState-backed Properties.
Below I’ve included a working page demonstrating what will be returned before and after the ViewState-backed Property is set. Enjoy!