Asp. NET tip: Rewrite viewstate storage destinations to improve page performance

Source: Internet
Author: User
Tags bind net return tostring visual studio
Asp.net| Skills | performance | page

In ASP.net, ViewState because in the client's HTML occupies a lot of space, and as the page postback repeatedly passed in the network, has been for human scale disease. But in fact ViewState can be stored anywhere in the database, cache, and so on, avoiding the frequent sending of lengthy base64 strings to clients. This will not only significantly improve performance (significantly reduce the number of bytes transmitted by the network), and if the content is not easily decrypted and cracked. Therefore, this method is very useful.

The following is a simple example of using caching as a ViewState storage destination. As for the cache Key, the article gives only a simple wording, concrete can be given according to the circumstances of the strict scheme.

The code is roughly illustrated as follows:

<%@ Page language= "C #" codebehind= "SaveViewStateToOther.aspx.cs" autoeventwireup= "false" inherits= " Linkedlist.saveviewstatetoother "%>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" >
<title>SaveViewStateToOther</title>
<meta name= "generator" content= "Microsoft Visual Studio. NET 7.1" >
<meta name= "Code_language" content= "C #" >
<meta name=vs_defaultclientscript content= "JavaScript" >
<meta name=vs_targetschema content= "http://schemas.microsoft.com/intellisense/ie5" >
<body ms_positioning= "GridLayout" >

<form id= "Form1" method= "POST" runat= "server" ><asp:datagrid id=datagrid1 "style=; left:104px; Position:absolute; top:72px "runat=" Server "bordercolor=" #3366CC "borderstyle=" None "borderwidth=" 1px "backcolor=" White "cellpadding=" 4 "Pagesize=" 6 "allowpaging=" True ">
<selecteditemstyle font-bold= "True" forecolor= "#CCFF99" backcolor= "#009999" >
</SelectedItemStyle>

<itemstyle forecolor= "#003399" backcolor= "White" >
</ItemStyle>

</HeaderStyle>

<footerstyle forecolor= "#003399" backcolor= "#99CCCC" >
</FooterStyle>

<pagerstyle horizontalalign= "left" forecolor= "#003399" backcolor= "#99CCCC" pagebuttoncount= "" mode= " NumericPages ">
</PagerStyle>
</asp:DataGrid>

</form>

</body>

Using System;
Using System.Data;
Using System.IO;
Using System.Text;
Using System.Web.UI;
Using System.Web.UI.WebControls;

Namespace LinkedList
{
<summary>
Summary description of the saveviewstatetoother.
</summary>
public class Saveviewstatetoother:page
{
protected DataGrid DataGrid1;

private void Page_Load (object sender, EventArgs e)
{
if (! IsPostBack)
Bind ();
}

        private void Bind ()
        {
            DataTable table = new DataTable ();
            table. Columns.Add ("id", typeof (int));
            table. Columns.Add ("name", typeof (String));

            for (int i = 0; i < 1000 i++)
             {
                 DataRow row = table. NewRow ();
                row["id"] = i;
                row["name" = " Student_ "+ i.tostring ();
                table. Rows.Add (row);
           }
            DataGrid1.DataSource = table;
            Datagrid1.databind ();
       }

Code generated #region the Web forms Designer

protected override void OnInit (EventArgs e)
{
InitializeComponent ();
Base. OnInit (e);
}

private void InitializeComponent ()
{
This. Datagrid1.pageindexchanged + = new System.Web.UI.WebControls.DataGridPageChangedEventHandler (this. datagrid1_pageindexchanged);
This. Load + = new System.EventHandler (this. Page_Load);

}

#endregion

protected override void Savepagestatetopersistencemedium (object viewState)
{
LosFormatter format = new LosFormatter ();
StringWriter writer = new StringWriter ();
Format. Serialize (writer, viewState);
String Vsraw = writer. ToString ();
byte[] buffer = convert.frombase64string (Vsraw);
String vstext = Encoding.ASCII.GetString (buffer);

Object v = Cache[pagekey];
if (v = = null)
Cache.Insert (Pagekey, Vstext);
Else
Cache[pagekey] = Vstext;
}

public string Pagekey
{
get {return Session.SessionID + "_page_saveviewstatetoother_aspx";}
}

protected override Object LoadPageStateFromPersistenceMedium ()
{
Object s = Cache[pagekey];
if (s!= null)
{
string state = S.tostring ();
byte[] buffer = Encoding.ASCII.GetBytes (state);
String vsraw = convert.tobase64string (buffer);
LosFormatter formatter = new LosFormatter ();
Return formatter. Deserialize (Vsraw);
}
return null;
}

private void Datagrid1_pageindexchanged (object source, DataGridPageChangedEventArgs e)
{
Datagrid1.currentpageindex = E.newpageindex;
Bind ();
}
}
}

For practical applications, if you want to decide to apply this scenario throughout the program, use a common page base class, where it is appropriate to implement this mechanism.

Source: Wood Wild Fox BLOG



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.