Pages

Advertisement

Friday, July 13, 2007

ASP.NET Tip: Create a ViewState Property

ASP.NET uses the ViewState to store data going back and forth to the server, eliminating the manual drudgery of reloading form controls and so forth. The ViewState can also be helpful for keeping your own state information, once you know how to read and write it. Using the ViewState can also eliminate nearly every case in which you would have used a hidden input field, a cookie, or a query string variable to pass information. It simply provides a cleaner way to pass your own information while your page is running.

Consider a simple situation that shows how this works in practice. In my applications, I typically have an ASP.NET page that lists my records, and then I have a user control to add and edit records of that type. The user control has an Add method and an Edit method, and the Edit method accepts the primary key of the record to edit. When the Edit method gets the primary key, it stores it in the ViewState so that when the user clicks the Save button, the user control knows which record to update. The following snippet of code illustrates this:

public void EditRecord(object recordID)
{
SelectedRecordID = recordID;
// Load record from database and show in control
}

protected object SelectedRecordID
{
get
{
return ViewState["SelectedRecordID"];
}
set
{
ViewState["SelectedRecordID"] = value;
}
}

The save code within the user control uses the SelectedRecordID property to save the changes back to the database. Because there's no query string or other way to move data from the "hosting" page to the user control, the ViewState fits the bill nicely.

You can also change the ViewState property to return a particular data type, such as an integer or other value. Before you return the value, make sure you first check that the ViewState value is not null (as shown below). This code sends back a -1 if there is no record selected, but you could return another appropriate value:

protected Int32 SelectedRecordID
{
get
{
if (ViewState["SelectedRecordID"] != null)
return Convert.ToInt32(ViewState["SelectedRecordID"]);
else
return -1;
}
set
{
ViewState["SelectedRecordID"] = value;
}
}

No comments:

Post a Comment