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”>
<Header>
<Keywords>
<Keyword>propv</Keyword>
</Keywords>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
<Title>SnippetFile1</Title>
<Author>Viktar</Author>
<Description>
</Description>
<HelpUrl>
</HelpUrl>
<Shortcut>propv</Shortcut>
</Header>
<Snippet>
<Declarations>
<Literal Editable=“true”>
<ID>MyProperty</ID>
<ToolTip>Property Name</ToolTip>
<Default>MyProperty</Default>
<Function>
</Function>
</Literal>
<Literal Editable=“true”>
<ID>int</ID>
<ToolTip>Type</ToolTip>
<Default>int</Default>
<Function>
</Function>
</Literal>
<Literal Editable=“true”>
<ID>DefaultValue</ID>
<ToolTip>DefaultValue</ToolTip>
<Default>0</Default>
<Function>
</Function>
</Literal>
</Declarations>
<Code Language=“csharp”><![CDATA[public $int$ $MyProperty$
{
get { return ($int$)(ViewState["$MyProperty$"] ?? $DefaultValue$); }
set { ViewState["$MyProperty$"] = value; }
}
]]></Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
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.