ASP.Net : Clean up your use of ViewState

Note: After reading this article, be sure to check out the followup article, "Using a STRUCT to make working with ViewState easier", where I take the ideas here and go one step further.

This is a big pet peeve of mine, so bear with me. I'll keep it short and to the point.

I'm a stickler for organized readable code and the use of ViewState is one of those things that can and should be standardized.

Typically you see developers directly access ViewState in the middle of doing other things. When you use this approach it means that when someone else reads through the code to maintain or enhance it, they have to look through all the code to see what is being placed in ViewState in order to know what they have to work with.

Let's jump right to my suggested approach and look at the code...

private int _EmployeeID = 0;
private byte[] _Version;
 
protected override object SaveViewState()
{
 this.ViewState.Add("_EmployeeID", _EmployeeID);
 this.ViewState.Add("_Version", _Version);
 return base.SaveViewState();
}
protected override void LoadViewState(object savedState)
{
 base.LoadViewState(savedState);
 _EmployeeID = (int)ViewState["_EmployeeID"];
 _Version = (Byte[])ViewState["_Version"];
}

Place the private variable declarations at the top of your module. You can follow immediately with the save and load overrides or move them elsewhere. I like having the save and load at the bottom of my code because I like to have my OnLoad be the first method in my code.

Why does it matter?

1. As I mentioned above it makes it easier for someone else to read your code and know what module level variables are being used. (Be sure to use a module level variable naming convention such as the _ prefix as well.)

2. ViewState is read once and written to once per variable rather than reading (and casting) it every time it's used in your code.

3. Because it makes you look like a professional. Seriously, take time to write clean organized code that follow standards and best practice approaches even when the module or page is very small.

[Edited 10/2/2007]

Alternate Approaches Suggested in the Comments Below

I like feedback and this post has some great feedback. My favorite, which honestly blew me away, is the attribute technique suggested by Tony. The full details can be found in the Code Project article, Using Attributes for encapsulating ASP.Net Session and ViewState variables. Declaring a variable on a page that is to be stored in ViewState is as simple as:

[PersistField(Location = PersistLocation.ViewState)]
protected int _EmployeeID;

To enable this you need to override the page class and create a custom attribute. If you already override the page class in your project then moving to this technique is almost a no-brainer.

What's so elegant about this besides the reduced about of code required, is that what you're doing is completely obvious since the variable is declared at the same place where you flag it for persistence via ViewState.

Another Approach

Michael Teper suggested the property approach.

private int _EmployeeId
{
 get { return (int) ViewState["_EmployeeId"]; }
 set { ViewState["_EmployeeId"] = value; }
}

If the attribute approach doesn't work for you, then this is probably the best way to handle ViewState, I've used it myself, but for some reason I've never changed my default coding approach to it. While this potentially reads values from ViewState multiple times, it doesn't do any reads if you don't use the property.

Published Saturday, September 29, 2007 11:37 AM by bschooley
Filed under:

Comments

# LINQ to SQL : Handling disconnected CRUD operations in ASP.Net

Saturday, September 29, 2007 5:37 PM by LINQing Out Loud

Most LINQ to SQL examples you find on the net tend to be written in a way that assumes a connected environment

# re: ASP.Net : Clean up your use of ViewState

Sunday, September 30, 2007 10:38 AM by MuteThis

I agree with you 100%, and I would like to add that IMO when a default value is required, it should be assigned in Page_Init.  That way on non-postbacks, the default value is present and on postback, the ViewState value is used.  Oh yeah, your post and my caveat are both predicated on the page life cycle and the assumption that you don't need the value until after LoadViewState, a.k.a. Page_Load, well process form data 1, but let's not too picky ;)

Ben

# re: ASP.Net : Clean up your use of ViewState

Monday, October 01, 2007 11:58 AM by jb

Thanks for the tip, but how many "Professional" ASP.Net developers use ViewState?

--jb

# re: ASP.Net : Clean up your use of ViewState

Monday, October 01, 2007 2:24 PM by Tony

Have a look at

www.codeproject.com/.../PersistAttribute.asp

you can declare a viewstate field as :

[PersistField(Location = PersistLocation.ViewState)]

protected int EmployeeID;

can be used for session as well.

# re: ASP.Net : Clean up your use of ViewState

Monday, October 01, 2007 4:32 PM by Michael Teper

I tend to write ViewState access into properties, like:

private int EmployeeId

{

  get { return (int) ViewState["EmployeeId"]; }

  set { ViewState["EmployeeId"] = value; }

}

I realize that it is less performant than your approach, but to my eye it is much easier to maintain because I dont need to chase down Save's and Load's any time I add a persisted property.

The attribute approach mentioned by Tony also looks interesting.

# Really nice method of determining where properties should be persisted to...

Tuesday, October 02, 2007 12:02 AM by mostlylucid

Really nice method of determining where properties should be persisted to...

# re: ASP.Net : Clean up your use of ViewState

Tuesday, October 02, 2007 8:31 AM by JeffL

I tend to do the following:

private int? _empId;

protected int? EmpId

{

 get

 {

   if ( _empId == null ) _empId = ViewState["EmpId"];

   return _empId;

 }

 set

 {

   if ( _empId == value ) return;

   _empId = value;

   ViewState["EmpId"] = _empId;

 }

}

This way I really only ever fetch the value if I ever need it. It also allows for the value to be read at any point, and I don't have to worry if the value has been fetched yet etc.

# re: ASP.Net : Clean up your use of ViewState

Tuesday, October 02, 2007 10:00 AM by bschooley

Tony! Thank you for pointing out the article on using attributes to drive ViewState. I'm already taking steps to integrate this technique into my future development.

Really... thanks to everyone for all the great suggestions. I've updated the post to include a couple.

The point of my post was to encourage people to stop referencing ViewState directly throughout their code. As the comments posted here show, there are multiple ways to go about it.

# re: ASP.Net : Clean up your use of ViewState

Tuesday, October 09, 2007 12:24 PM by AndrewSeven

People use Viewstate directly from "wherever" in code?

Not me; I can't recall others doing so either, I would have told them to use properties.

I occasionally resort to Load and Save Viewstate but not for simple properties.

The thing about using properties is that they work well with DefaultValueAttribute and viewstate tracking.

# re: ASP.Net : Clean up your use of ViewState

Wednesday, March 11, 2009 7:04 PM by ...

Gute Arbeit hier! Gute Inhalte.

# re: ASP.Net : Clean up your use of ViewState

Thursday, March 12, 2009 6:06 PM by ...

Sehr wertvolle Informationen! Empfehlen!

# re: ASP.Net : Clean up your use of ViewState

Tuesday, February 15, 2011 2:53 AM by Divya

what is cleaning up solution in ASP.NET code?

Leave a Comment

(required) 
(required) 
(optional)
(required)