Correct way of storing c# property in ViewState

It’s very useful to store control or page properties in ViewState. For example, you have ArticleId which comes from QueryString. You need to verify QueryString parameters format and make sure that this is not a hack attempt. If it is in the correct format, then make sure that an article exists in the database, etc. After a postback, you need to do this all over again. However you can store verified ArticleId in ViewState, so after the postback, you don’t need to do verification all over again.

I used to store c# property in ViewState as following:

public int AritcleId
    get { return ViewState["AritcleId"] != null ? (int)ViewState["AritcleId"] : 0; }
    set { ViewState["AritcleId"] = value; }

I even created a snippet for this. I knew about ?? c# operator, but never really used it. However, ViewState property is a classic example for a null-coalescing operator. The code above can be rewritten like this:

public int AritcleId
    get { return (int)(ViewState["AritcleId"] ?? 0); }
    set { ViewState["AritcleId"] = value; }

And here is a code snippet:

<?xml version=“1.0” encoding=“utf-8”?>
<CodeSnippets xmlns=“http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format=“1.0.0”>
        <Literal Editable=“true”>
        <ToolTip>Property Name</ToolTip>
        <Literal Editable=“true”>
        <Literal Editable=“true”>
        <Code Language=“csharp”><![CDATA[public $int$ $MyProperty$
            get { return ($int$)(ViewState["$MyProperty$"] ?? $DefaultValue$); }
            set { ViewState["$MyProperty$"] = value; }

You can create, change and manage code snippets using Snippet Designer. Don’t forget to encrypt your ViewState as described in Encrypt ViewState in ASP.NET MSDN article.

Posted on December 14, 2008 by


Posted on 10/28/2014 11:09:24 PM by Akshay Halasangi

Hello there,

This was awesome learning for me. I would want you to emphasize on what goes in the ViewState property though. Newbies like me will be lost as in what goes inside. Though it is obvious enough from the code that the property name as a string should be going in with a type case but still many beginners will make that mistake.

Thank you for this post.