Friday, November 14, 2008

Tip for Managing Keys for QueryString, ViewState, Session, Etc.

When developing web applications you always have to manage all those "names" for the QueryString, ViewState, Session, etc. and its good to have consistent and "typed" way to too keep track of that stuff.

To manage this information on a per page basis I simply create private classes within the page so I can have a typed way of accessing these keys. For example:


namespace GTTPatentSearchWeb.Search
{
public partial class ViewPatent : System.Web.UI.Page
{
private class QueryStringKeys
{
public const string PatentId = "PatentId";
public const string UserId = "Uid";
public const string RegionId = "Rid";
}

private class ViewStateKeys
{
public const string SelectedPatentId = "SelPatentId";
public const string IsNew = "IsNew";
}

public int PatentId
{
get
{
object patentId = Request.QueryString[QueryStringKeys.PatentId];
if (patentId != null)
{
return Convert.ToInt32(patentId);
}

return -1;
}
}

...

As you can see this provides a nice typed method for managing keys rather than trying to remember the names you used throughout the page.
For SessionKeys I generally will create a global class in App_Code to manage the SessionKeys since they cross page and not specific to the page itself. This prevents me from accidentally using a SessionKey in 2 places in application not realizing it had already been used.

Have a great day!

No comments: