|
ent sort order for a static
list of data in ViewState.<br>
Click the link in the column header to sort the data by that field.<br>
Click the link a second time to reverse the sort direction.
<br><br><br>
<asp:datagrid id="DataGrid1" runat="server" OnSortCommand="SortGrid"
BorderStyle="None" BorderWidth="1px" BorderColor="#CCCCCC"
BackColor="White" CellPadding="5" AllowSorting="True">
<HeaderStyle Font-Bold="True" ForeColor="White" BackColor="#006699">
</HeaderStyle>
</asp:datagrid>
</P>
</form>
</body>
</HTML>
<script runat="server">
// SortField property is tracked in ViewState
string SortField {
get {
object o = ViewState["SortField"];
if (o == null) {
return String.Empty;
}
return (string)o;
}
set {
if (value == SortField) {
// same as current sort file, toggle sort direction
SortAscending = !SortAscending;
}
ViewState["SortField"] = value;
}
}
// SortAscending property is tracked in ViewState
bool SortAscending {
get {
object o = ViewState["SortAscending"];
if (o == null) {
return true;
}
return (bool)o;
}
set {
ViewState["SortAscending"] = value;
}
}
void Page_Load(object sender, EventArgs e) {
if (!Page.IsPostBack) {
BindGrid();
}
}
void BindGrid() {
// get data
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("TestData.xml"));
DataView dv = new DataView(ds.Tables[0]);
// Apply sort filter and direction
dv.Sort = SortField;
if (!SortAscending) {
dv.Sort += " DESC";
}
// Bind grid
DataGrid1.DataSource = dv;
DataGrid1.DataBind();
}
void SortGrid(object sender, DataGridSortCommandEventArgs e) {
DataGrid1.CurrentPageIndex = 0;
SortField = e.SortExpression;
BindGrid();
}
</script>
Here''''s the code for testdata.xml, referenced in both code sections above: <?xml version="1.0" standalone="yes"?>
<NewDataSet>
<Table>
<pub_id>0736</pub_id>
<pub_name>New Moon Books</pub_name>
<city>Boston</city>
<state>MA</state>
<country>USA</country>
</Table>
<Table>
<pub_id>0877</pub_id>
<pub_name>Binnet & Hardley</pub_name>
<city>Washington</city>
<state>DC</state>
<country>USA</country>
</Table>
<Table>
<pub_id>1389</pub_id>
<pub_name>Algodata Infosystems</pub_name>
<city>Berkeley</city>
<state>CA</state>
<country>USA</country>
</Table>
<Table>
<pub_id>1622</pub_id>
<pub_name>Five Lakes Publishing</pub_name>
<city>Chicago</city>
<state>IL</state>
<country>USA</country>
</Table>
<Table>
<pub_id>1756</pub_id>
<pub_name>Ramona Publishers</pub_name>
<city>Dallas</city>
<state>TX</state>
<country>USA</country>
</Table>
<Table>
<pub_id>9901</pub_id>
<pub_name>GGG&G</pub_name>
<city>München</city>
<country>Germany</country>
</Table>
<Table>
<pub_id>9952</pub_id>
<pub_name>Scootney Books</pub_name>
<city>New York</city>
<state>NY</state>
<country>USA</country>
</Table>
<Table>
<pub_id>9999</pub_id>
<pub_name>Lucerne Publishing</pub_name>
<city>Paris</city>
<country>France</country>
</Table>
</NewDataSet>
Session State or ViewState?
There are certain cases where holding a state value in ViewState is not the best option. The most commonly used alternative is Session state, which is generally better suited for:
- Large amounts of data. Since ViewState increases the size of both the page sent to the browser (the HTML payload) and the size of form posted back, it''''s a poor choice for storing large amounts of data.
- Secure data that is not already displayed in the UI. While the ViewState data is encoded and may optionally be encrypted, your data is most secure if it is never sent to the client. So, Session state is a more secure option. (Storing the data in the database is even more secure due to the additional database credentials. You can add SSL for even better link security.) But if you''''ve displayed the private data in the UI, presumably you''''re already comfortable with the security of the link itself. In this case, it is no less secure to put the same value into ViewState as well.
- Objects not readily serialized into ViewState, for example, DataSet. The ViewState serializer is optimized for a small set of common object types, listed below. Other types that are serializable may be persisted in ViewState, but are slower and generate a very large ViewState footprint.
| |
Session State |
ViewState |
Holds server resources?
Yes
No
Times out?
Yes – after 20 minutes (default)
No
Stores any .NET type?
Yes
No, limited support for: strings, integers, Booleans, arrays, ArrayList, hashtable, custom TypeConverters
Increases "HTML payload"?
No
Yes
Getting the Best Performance with ViewState
Each object must be serialized going into ViewState and then deserialized upon post back, so the performance cost of using ViewState is definitely not free. However, there''''s usually no significant performance impact if you follow some simple guidelines to keep your ViewState costs under control.
- Disable ViewState when you don''''t need it. The next section, Getting Less from ViewState, covers this in detail.
- Use the optimized ViewState serializers. The types listed above have special serializers that are very fast and optimized to produce a small ViewState footprint. When you want to serialize a type not listed above, you can greatly improve its performance by creating a custom TypeConverter for it.
- Use the fewest number of objects, and if possible, reduce the number of objects you put into ViewState. For example, rather than a two-dimensional string array of names/values (which has as many objects as the length of the array), use two string arrays (only two objects). However, there is usually no performance benefit to convert between two known types before storing them in ViewState—then you''''re basically paying the conversion price twice.
Getting Less from ViewState
ViewState is enabled by default, and it''''s up to each control—not the page developer—to decide what gets stored in ViewState. Sometimes, this information is not useful to your application. While it''''s not harmful either, it can dramatically increase the size of the page sent to the browser. It''''s a good idea to turn off ViewState if you are not using it, especially where the ViewState size is significant.
You can turn off ViewState on a per-control, per-page, or even per-application basis. You don''''t need ViewState if:
Pages |
Controls |
- The page doesn''''t post back to itself.
- You aren''''t handling the control''''s events.
- The control has no dynamic or data bound property values (or they are set in code on every request).
The DataGrid control is a particularly heavy user of ViewState. By default, all of the data displayed in the grid is also stored in ViewState, and that''''s a wonderful thing when an expensive operation (like a complex search) is required to fetch the data. However, this behavior also makes DataGrid the prime suspect for unnecessary ViewState.
For example, here''''s a simple page that meets the criteria above. ViewState is not needed because the page doesn''''t post back to itself.

Figure 3. Simple page LessViewState.aspx with DataGrid1
<%@ Import Namespace="System.Data" %>
<html>
<body>
<form runat="server">
<asp:DataGrid runat="server" />
</form>
</body>
</html>
<script runat="server">
Private Sub Page_Load(sender As Object, e As EventArgs)
Dim ds as New DataSet()
ds.ReadXml(Server.MapPath("TestData.xml"))
DataGrid1.DataSource = ds
DataGrid1.DataBind()
End Sub
</script>
With ViewState enabled, this little grid contributes over 3000 bytes to the HTML payload for the page! You can see this using ASP.NET Tracing, or by viewing the source of the page sent to the browser, as shown in the code below.
<HTML>
<HEAD>
<title>Reducing Page "HTML P上一页 [1] [2] [3] [4] 下一页
[办公软件]Word表格中Shift+Alt+方向键的妙用 [系统软件]A REVIEW OF SQLEXPLORER PLUG-IN
[VB.NET程序]Read a string at a given address [VB.NET程序]Read a byte, integer or long from memory
[Delphi程序]// I have a comment ----Delphi 研发人员谈注释 … [Delphi程序]// I have a comment ----Delphi 研发人员谈注释
[Delphi程序]Creating a real singleton class in Delphi 5 [Delphi程序]Download a file from a FTP Server
[Delphi程序]2004.11.29.Starting a Project [Delphi程序]How can I create a tray icon