Let's say you have a very large DropDownList with lots of values and text. We need to maintain ViewState in this DropDownList so that we can retrieve the selected value on a post back. Of course, this means that now the ViewState contains the data for every single value in the list, both values and text included. Even though the page itself may be fairly simple and lightweight, the result of having this simple DropDownList on the page is that the page size is quite large and the amount of data passed back and forth on a postback is very large as well.
If you have an efficient database, and/or if you are caching the data anyway, you might not mind re-loading the list items each time the page posts back to eliminate the need for the page itself to hold all of this ViewState data.
However, if you turn off ViewState on the DropDownList, you will notice that it now does not remember the selected value on post backs. The solution is very simple -- just manually set the DropDownList after re-loading it to the value from the HTML form post.
To do this, first we disable ViewState on the DropDownList (EnableViewState="False"). Then, instead of a typical PageLoad() method like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
loadList();
// other stuff here
}
}
we would load the list every time the page posts back:
protected void Page_Load(object sender, EventArgs e)
{
loadList();
if (!IsPostBack)
{
// other stuff here
}
}
And, in that loadList() method, instead of simply doing this:
void loadList()
{
dlTest.DataSource = // get data from DB
dlTest.DataBind();
}
you also would check to see if it has a posted value:
void loadList()
{
dlTest.DataSource = // get data from DB
dlTest.DataBind();
string r = Request[dlTest.UniqueID];
if (r != null)
dlTest.SelectedValue = r;
}
That loads the DropDownList each time and ensures that the value set is what was posted back. Thus, the control will now "remember" the selected value on each postback, but without requiring any data stored in the ViewState at all.
It would also be easy to implement this logic in a control that inherits from DropDownList; say, a LightDropDownList. Techniques like this will of course work on other controls as well, such as a ListBox or a CheckedList.
With fast database connections and performance, as well as data caching, sometimes persisting data on the page is not the optimal way to go. Like always, there are different ways to skin a cat and sometimes simple little tweaks like this can have huge benefits on performance.
Update: See the comments for other options are that even easier/better. Also in the comments, Richard has provided a link to this
excellent post on ViewState that I highly recommend checking out. It's long, but very informative and quite entertaining as well. Thanks for the great feedback.