ASP.NET ViewState

xiaoxiao2021-03-06  87

Susan Warren

Microsoft Corporation

When talking to the developer who just contacted the ASP.NET page, they usually give me the first question is: "What is the viewstate?" The feeling of their tone, just like I came to a foreign country. The feelings of the waiter, the feeling of the waiter, I have never seen any dishes - I don't understand, but also curious. But there is certain that someone thinks it is good, otherwise it will not provide. So, I will try it first, may like it, although it looks really quirky!

This is also true for ViewState, but if you adapt to its style, you will find that in many cases, you will be happy to use ViewState in your own ASP.NET application, because it can help you use less code to do more jobs. However, sometimes it is completely abandoned for ViewState. Below we will elaborate on both cases, but let us answer what is ViewState.

Answer: ViewState is used to maintain the UI status of the page

The web is not status, the ASP.NET page is not status, which is instantiated, executed, rendered, and processed during each round-trip process of the server. As a web developer, you can use well-known technologies (such as stored on the server in a session state, or return the page back to itself). Below we are discussed as an example in Figure 1.

Figure 1: Restore the flexible form value

As can be seen from the figure, I chose an invalid value for the lunch meal. This form is as friendly as most forms on the Web, which displays a useful error message next to the error field and an asterisk. Moreover, all values ​​I have entered in other text boxes and drop-down lists are also shown. This is somewhat possible because the HTML form element sends its current value from the browser to the server in the HTTP header. You can use ASP.NET trackers to view the return form value, as shown in Figure 2.

Figure 2: Retrieved value in the HTTP form (display via ASP.NET tracking)

Before ASP.NET, the value is restored to the value of the value to the Form field through multiple times, they will have to pick up the return value from the HTTP form, and then push it back in the field. Fortunately, now ASP.NET can automatically complete this task, so that the developer eliminates an annoying job, but also does not need to write a lot of code for the form. But this is not ViewState.

ViewState is a mechanism, ASP.NET uses this mechanism to track server control status values, otherwise these values ​​will not be sent back as part of the HTTP form. For example, the text displayed by the Label control is saved in ViewState by default. As a developer, you can bind the data, or only set up the Label programming when loading this page. In subsequent return, the label text will automatically refill from ViewState. Therefore, in addition to cumbersome work and code, ViewState can also reduce the number of round trips of the database.

ViewState works

ViewState does not have any mystery, which is a hidden form field managed by the ASP.NET page framework. When ASP.NET performs a page, the viewState value and all controls on this page will be collected and formatted into an encoded string, and then assigned to the value attribute of the hidden form field (ie ) . Since the hidden form field is part of the page sent to the client, the ViewState value is temporarily stored in the client's browser. If the client selects the page back to the server, the ViewState string will also be passed back. The viewState form field and its return value can be seen in Figure 2 above. After passing, the ASP.NET page frame will parse the ViewState string and populate the ViewState property for the page and each control. The control then uses ViewState data to restore yourself to the previous state.

About ViewState has three small problems worth noting.

If you want to use ViewState, you must have a server-side form tag (

) in the ASPX page. The form field is required so that the hidden field containing ViewState information can pass back to the server. Moreover, the form must also be a server-side form, so that when the page is executed on the server, the ASP.NET page framework can add hidden fields.

The page itself saves 20-byte information in ViewState to send the postback data and the ViewState value to the correct control at the time of return. Therefore, even if the page or application is disabled, you can still see a small amount of remaining bytes in ViewState.

In the case where the page does not return, the ViewState in the page can be removed by omitting the tag of the server.

Take advantage of ViewState

ViewState provides a magical way to the status of the transmission tracking control because it does not use server resources, and it will not be overtime and apply to any browser. If you want to write controls, then you must need to know how to maintain the status in the control (English).

The developer can also use ViewState in almost the same way, but sometimes the page will contain a UI status value that is not stored. You can track the values ​​in ViewState, using the programming syntax using the session and the syntax of the cache:

[Visual Basic]

'Save in ViewState

ViewState ("Sortorder") = "DESC"

'Read from ViewState

DIM Sortorder As String = CSTR (ViewState ("Sortorder"))

[C #]

// Save in ViewState

ViewState ["Sortorder"] = "DESC";

/ / Read from ViewState

String Sortorder = (String) ViewState ["Sortorder"];

Please see the example below: To display a list of items on the web page, and each user needs different list sort. The list of items is static, so they can bind these pages to the same cache dataset, and the sort order is only a small portion of the user-specific UI state. ViewState is ideal for storing this type of value. code show as below:

[Visual Basic]

<% @ Import namespace = "system.data"%>

for ViewState / Title for page UI status></p> <p></ HEAD></p> <p><body></p> <p><form runat = "server"></p> <p><H3></p> <p>Storage non-control status in ViewState</p> <p></ H3></p> <p><P></p> <p>This example stores the current sorting order of a column of static data in ViewState.</p> <p>Click the link in the column header to sort the data according to this field.</p> <p>Click this link again to sort in the reverse order.</p> <p><ask: DataGrid ID = "DataGrid1" runat = "server"</p> <p>OnSortCommand = "sortgrid" border = "none" borderwidth = "1px"</p> <p>Bordercolor = "# cccccc" backcolor = "white" cellpadding = "5" allowsorting = "true"></p> <p><Headersty font-bold = "true" forcolor = "White"</p> <p>Backcolor = "# 006699"></p> <p></ Headerstyle></p> <p></ ask: DataGrid></p> <p></ P></p> <p></ form></p> <p></ body></p> <p></ Html></p> <p><script runat = "server"></p> <p>'Tracking Sortfield properties in ViewState</p> <p>Property Sortfield () AS STRING</p> <p>Get</p> <p>Dim o as object = viewState ("sortfield")</p> <p>IF o is nothing then</p> <p>Return String.empty</p> <p>END IF</p> <p>Return CSTR (O)</p> <p>END GET</p> <p>Set (Value As String)</p> <p>IF value = sortfield then</p> <p>'Same as the current sort file, switching</p> <p>Sortascending = not Sortascending</p> <p>END IF</p> <p>ViewState ("sortfield") = value</p> <p>End set</p> <p>End Property</p> <p>'Tracking Sortascending properties in ViewState</p> <p>Property Sortascending () AS Boolean</p> <p>Get</p> <p>Dim o as object = viewState ("sortascending")</p> <p>IF o is nothing then</p> <p>Return True</p> <p>END IF</p> <p>Return CBOOL (O)</p> <p>END GET</p> <p>Set (Value As Boolean)</p> <p>ViewState ("Sortascending") = value</p> <p>End set</p> <p>End Property</p> <p>Private Sub Page_Load (Sender As Object, E AS Eventargs) Handles MyBase.Load</p> <p>IF not page.ispostback then</p> <p>Bindgrid ()</p> <p>END IF</p> <p>End Sub</p> <p>Sub bindgrid ()</p> <p>' retrieve data</p> <p>DIM DS AS New DataSet ()</p> <p>DS.Readxml (Server.Mappath ("TestData.xml")) DIM DV AS New DataView (ds.tables (0))</p> <p>'Apply Sorting Filters and Directions</p> <p>Dv.Sort = Sortfield</p> <p>IF not Sortascending Then</p> <p>Dv.Sort = "DESC"</p> <p>END IF</p> <p>'Binding Grid</p> <p>DataGrid1.datasource = DV</p> <p>DataGrid1.databind ()</p> <p>End Sub</p> <p>Private Sub Sortgrid (Sender As Object, E AS DataGridsortCommandeventAndArgs)</p> <p>DataGrid1.currentPageIndex = 0</p> <p>Sortfield = E.Sortexpression</p> <p>Bindgrid ()</p> <p>End Sub</p> <p></ script></p> <p>[C #]</p> <p><% @ Page language = "c #"%></p> <p><% @ Import namespace = "system.data"%></p> <p><Html></p> <p><HEAD></p> <p><title> ViewState </ Title> for page UI status values</p> <p></ HEAD></p> <p><body></p> <p><form runat = "server"></p> <p><H3></p> <p>Storage non-control status in ViewState</p> <p></ H3></p> <p><P></p> <p>This example stores the current sorting order of a column of static data in ViewState.</p> <p>Click the link in the column header to sort the data according to this field.</p> <p>Click this link again to sort in the reverse order.</p> <p><ask: dataGrid id = "dataGrid1" runat = "server" onsortcommand = "sortgrid"</p> <p>BorderStyle = "none" borderwidth = "1px" bordercolor = "# cccccc"</p> <p>Backcolor = "White" cellpadding = "5" allowsorting = "true"></p> <p><Headerstyle font-bold = "true" forcolor = "White" backcolor = "# 006699"></p> <p></ Headerstyle></p> <p></ ask: DataGrid></p> <p></ P></p> <p></ form></p> <p></ body></p> <p></ Html></p> <p><script runat = "server"></p> <p>// Track the Sortfield property in ViewState</p> <p>String sortfield {</p> <p>Get {</p> <p>Object o = viewState ["sortfield"];</p> <p>IF (o == null) {</p> <p>Return string.empty;</p> <p>}</p> <p>Return (String) O;</p> <p>}</p> <p>SET {</p> <p>IF (value == sortfield) {</p> <p>/ / The same as the current sort file, switch sorting direction</p> <p>Sortascending =! Sortascending;</p> <p>}</p> <p>ViewState ["sortfield"] = value;</p> <p>}</p> <p>// Track the Sortascending property in ViewState</p> <p>Bool sortascending {</p> <p>Get {</p> <p>Object o = viewState ["sortascending"];</p> <p>IF (o == null) {</p> <p>Return True;</p> <p>}</p> <p>Return (BOOL) O;</p> <p>}</p> <p>SET {</p> <p>ViewState ["Sortascending"] = Value;</p> <p>}</p> <p>}</p> <p>Void Page_Load (Object Sender, Eventargs E) {</p> <p>IF (! page.ispostback) {</p> <p>Bindgrid ();</p> <p>}</p> <p>}</p> <p>Void bindgrid () {</p> <p>// retrieve data</p> <p>DataSet DS = New Dataset ();</p> <p>DS.Readxml (Server.Mappath ("TestData.xml");</p> <p>DataView DV = New DataView (ds.tables [0]);</p> <p>// Applied sort filter and direction</p> <p>Dv.sort = sortfield;</p> <p>IF (! sortascending) {</p> <p>Dv.Sort = "DESC";</p> <p>}</p> <p>// Bind mesh</p> <p>DataGrid1.datasource = DV;</p> <p>DataGrid1.databind ();</p> <p>}</p> <p>Void Sortgrid (Object Sender, DataGridSortCommandeventEventArgs E) {</p> <p>DataGrid1.currentpageIndex = 0;</p> <p>Sortfield = E.Sortexpression;</p> <p>Bindgrid ();</p> <p>}</p> <p></ script></p> <p>The following is the code referenced by the TestData.xml referenced in the above two code segments:</p> <p><? XML Version = "1.0" Standalone = "YES"?></p> <p><NewDataSet></p> <p><Table></p> <p><Pub_ID> 0736 </ PUB_ID></p> <p><pub_name> new moon books </ pub_name></p> <p><city> boston </ city></p> <p><state> ma </ state></p> <p><country> USA </ country></p> <p></ TABLE></p> <p><Table></p> <p><Pub_ID> 0877 </ PUB_ID></p> <p><Pub_Name> Binnet & Hardley </ Pub_Name></p> <p><city> Washington </ city></p> <p><State> DC </ state></p> <p><country> USA </ country></p> <p></ TABLE></p> <p><Table></p> <p><Pub_ID> 1389 </ PUB_ID></p> <p><pub_name> Algodata Infosystems </ pub_name></p> <p><city> Berkeley </ city></p> <p><State> CA </ state></p> <p><country> USA </ country></p> <p></ TABLE></p> <p><Table></p> <p><Pub_ID> 1622 </ PUB_ID></p> <p><pub_name> Five Lake Publishing </ Pub_Name> <City> Chicago </ city></p> <p><State> Il </ state></p> <p><country> USA </ country></p> <p></ TABLE></p> <p><Table></p> <p><Pub_ID> 1756 </ PUB_ID></p> <p><pub_name> Ramona Publishers </ PUB_NAME></p> <p><city> dallas </ city></p> <p><State> TX </ state></p> <p><country> USA </ country></p> <p></ TABLE></p> <p><Table></p> <p><Pub_ID> 9901 </ PUB_ID></p> <p><pub_name> GGG & g </ pub_name></p> <p><city> Muenchen </ city></p> <p><country> germany </ country></p> <p></ TABLE></p> <p><Table></p> <p><Pub_ID> 9952 </ PUB_ID></p> <p><pub_name> Scootney Books </ PUB_NAME></p> <p><city> new york </ city></p> <p><State> NY </ state></p> <p><country> USA </ country></p> <p></ TABLE></p> <p><Table></p> <p><Pub_ID> 9999 </ PUB_ID></p> <p><pub_name> Lucerne Publishing </ PUB_NAME></p> <p><city> Paris </ city></p> <p><country> France </ country></p> <p></ TABLE></p> <p></ NewDataSet></p> <p>Select a session status or viewstate?</p> <p>In some cases, save the status value in ViewState is not the best choice. The most common alternative is the session state, which is usually more suitable for:</p> <p>massive data. Since ViewState adds the size of the page sent to the browser (HTML payload), it also increases the size of the return form, so it is not suitable for storing a large amount of data.</p> <p>Secure data is not displayed in the UI. Although the viewState data has been encoded and can be encrypted, it is the safest to send data to the client. Therefore, the session is a safer option. (Since the database requires additional credentials to verify, the data is stored in the database will be safer. You can add SSL to get a more secure link.) However, if the private data has been displayed in the UI, then you should have confirmed The security of the link. In this case, the same value is placed in ViewState does not reduce security.</p> <p>The objects that have not been serially entered to ViewState, such as DataSet. The ViewState serialization program is optimized for a small part of the commonly used object type, as shown below. Other sequential types may be kept in ViewState, but the speed will slow down and generate a very large viewState.</p> <p>Session status ViewState</p> <p>Do you use server resources? Yes</p> <p>Is it timeout? Yes, after 20 minutes (default)</p> <p>Do you store all .NET types? Yes No, only support: string, integer, boolean, array, arraylist, hashtable, and custom TypeConverter add "HTML payload"? no Yes</p> <p>Get the best performance using ViewState</p> <p>When using ViewState, each object must be serialized in ViewState and then retrore sequencing by backhaul, so it is not cost to use ViewState. However, if you follow some simple principles to control the cost of ViewState, it usually does not have a significant performance impact.</p> <p>Disable ViewState when you don't need it. The following "Reduce Using ViewState" section will detail this question.</p> <p>Use optimized ViewState serialization procedures. The types listed above have specialized serialization procedures, which are running quickly and have been optimized, which can generate small ViewState. If you want to serialize a type not listed above, you can create a custom TypeConverter to significantly improve its performance.</p> <p>Try to minimize the use object, if possible, minus the number of objects placed in ViewState. For example, do not use a two-dimensional string array (name / value, the number of objects is as much as the length of the array), but should use two string arrays (only two objects). However, before the two known types are stored in ViewState, the conversion between the two will not obtain any performance improvement, as this is actually equivalent to paying the cost of twice.</p> <p>Reduce using ViewState</p> <p>By default, ViewState will be enabled and is determined by each control (not the page developer) to determine the content stored in ViewState. Sometimes this information is not used by the application. Although there is no harm, it will significantly increase the size of the page sent to the browser. So if you don't need to use ViewState, it is best to turn it off, especially when ViewState is large.</p> <p>You can close ViewState based on each control, each page, or each application. You will no longer need ViewState in the following cases:</p> <p>Page control</p> <p>The page does not return to itself.</p> <p>Processing is not an event of a control.</p> <p>The control does not have a dynamic or data binding attribute value (or it is set in the code for each request).</p> <p>The DataGrid control is a heavyweight user of ViewState. By default, all data displayed in the grid is also stored in ViewState, which is very useful when a complex operation (such as complex search) is required to obtain data. However, this behavior of DataGrid sometimes makes viewState become cumbersome.</p> <p>For example, there is a simple page that is the above. Because the page does not return to itself, it does not need ViewState.</p> <p>Figure 3: Simple page with DataGrid1 LessViewState.aspx</p> <p><% @ Import namespace = "system.data"%></p> <p><html></p> <p><body></p> <p><form runat = "server"></p> <p><asp: datagrid runat = "server" /></p> <p></ form></p> <p></ body></p> <p></ html></p> <p><script runat = "server"></p> <p>Private subject (Sender As Object, E AS Eventargs) DIM DS AS NEW DATASET ()</p> <p>DS.Readxml (Server.MAppath ("TestData.xml"))</p> <p>DataGrid1.datasource = DS</p> <p>DataGrid1.databind ()</p> <p>End Sub</p> <p></ script></p> <p>When ViewState is enabled, this small grid adds more than 3,000-multi-byte HTML payload! Use ASP.NET TRACING (English) or view the source code of the page sent to the browser (as shown in the following code), you can clearly see this.</p> <p><Html></p> <p><HEAD></p> <p><title> Reduce the page "HTML payload" </ Title></p> <p></ HEAD></p> <p><body></p> <p><form name = "_ CTL0" method = "post" action = "lessviewstate.aspx" id = "_ ctl0"></p> <p><Input Type = "Hidden" name = "__ viewstate"</p> <p>Value = "DDWXNTGZOTU2ODA7DDW7BDXPPDE OZ47BDX0PDTSPGK8MT47PJTSPHQ8QDA8CDXW</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47PJ47PJ47PJ47PJ47PJ47PG == "/></p> <p>Look! Just disable the viewstate of the grid, the payload of the same page is greatly reduced:</p> <p><Html></p> <p><HEAD></p> <p><title> Reduce the page "HTML payload" </ Title></p> <p></ HEAD></p> <p><body></p> <p><form name = "_ CTL0" method = "post" action = "lessviewstate.aspx" id = "_ ctl0"></p> <p><Input Type = "Hidden" name = "__ viewstate" value = "ddwxntgzotu2oda7oz4 =" /></p> <p>Here is the complete LessViewState code of Visual Basic and C #:</p> <p>[Visual Basic]</p> <p><% @ Import namespace = "system.data"%></p> <p><html></p> <p><HEAD></p> <p><title> Reduce the page "HTML payload" </ Title></p> <p></ HEAD></p> <p><body></p> <p><form runat = "server"></p> <p><H3></p> <p>Reduce the "HTML payload" of the page by disabling ViewState</p> <p></ H3></p> <p><P></p> <p><ask: DATAGRID ID = "DataGrid1" runat = "server" enableviewstate = "false"</p> <p>Borderstyle = "none" borderwidth = "1px" bordercolor = "# cccccc" backcolor = "white" cellpadding = "5"></p> <p><Headerstyle font-bold = "true" forcolor = "White" backcolor = "# 006699"></p> <p></ Headerstyle></p> <p></ ask: DataGrid></p> <p></ P></p> <p></ form></p> <p></ body></p> <p></ html> <script runat = "server"></p> <p>Private subject (Sender As Object, E AS Eventargs)</p> <p>DIM DS AS New DataSet ()</p> <p>DS.Readxml (Server.MAppath ("TestData.xml"))</p> <p>DataGrid1.datasource = DS</p> <p>DataGrid1.databind ()</p> <p>End Sub</p> <p></ script></p> <p>[C #]</p> <p><% @ Page language = "c #"%></p> <p><% @ Import namespace = "system.data"%></p> <p><html></p> <p><HEAD></p> <p><title> Reduce the page "HTML payload" </ Title></p> <p></ HEAD></p> <p><body></p> <p><form runat = "server"></p> <p><H3></p> <p>Reduce the "HTML payload" of the page by disabling ViewState</p> <p></ H3></p> <p><P></p> <p><ask: DATAGRID ID = "DataGrid1" runat = "server" enableviewstate = "false"</p> <p>BorderStyle = "none" borderwidth = "1px" bordercolor = "# cccccc"</p> <p>Backcolor = "White" cellpadding = "5"></p> <p><Headerstyle font-bold = "true" forcolor = "White" backcolor = "# 006699"></p> <p></ Headerstyle></p> <p></ ask: DataGrid></p> <p></ P></p> <p></ form></p> <p></ body></p> <p></ html></p> <p><script runat = "server"></p> <p>Void Page_Load (Object Sender, Eventargs E) {</p> <p>DataSet DS = New Dataset ();</p> <p>DS.Readxml (Server.Mappath ("TestData.xml");</p> <p>DataGrid1.datasource = DS;</p> <p>DataGrid1.databind ();</p> <p>}</p> <p></ script></p> <p>Disable viewState</p> <p>In the above example, I disabled ViewState by setting the grid's enableViewState property to false. You can disable ViewState for a single control, the entire page, or the entire application, as shown below: Each control (on the tag) <ask: DataGrid enableViewState = "false"? /></p> <p>Each page (in the instruction) <% @ Page EnableViewState = "false"?%></p> <p>Each application (in Web.Config) <piece enableviewstate = "false"? /></p> <p>Make ViewState safer</p> <p>Since viewState is not formatted to clear text, some people sometimes think it is encrypted, but there is no. Instead, ViewState is just based on Base64 encoding to ensure that the value does not change during the round-trip process, and does not consider the response / request coding used by the application.</p> <p>You can add two ViewState security levels to your application:</p> <p>Tamper</p> <p>encryption</p> <p>It should be noted that viewState security has a direct impact on the time required to process and present the ASP.NET page. Simply put, the higher the safety, the slower the speed. So if you don't need it, please don't add security for ViewState.</p> <p>Tamper</p> <p>Although the hash code does not ensure the security of the actual data in the ViewState field, it can significantly reduce the likelihood that someone defrauds the application through ViewState, ie, prevents the return application usually prohibits the value of the user.</p> <p>You can indicate a hash code to the ViewState field by setting the enableviewStateMac property:</p> <p><% @ Page EnableViewStateMac = true%></p> <p>EnableViewStateMac can be set on the page level, or you can set it at the application level. At the time of return, the ASP.NET will generate a hash code for the ViewState data and compare it with the hash code stored in the return value. If the hash code does not match, the viewState data will be discarded, while the control will be restored to the original settings.</p> <p>By default, ASP.NET uses the SHA1 algorithm to generate the ViewState hash code. In addition, the MD5 algorithm can also be selected by setting <MachineKey> in the Machine.config file, as shown below:</p> <p><MachineKey Validation = "MD5" /></p> <p>encryption</p> <p>Encryption can be used to protect the actual data values ​​in the ViewState field. First, EnableViewStatmac = "True" must be set as described above. Then, set the MachineKey Validation type to 3DES. This will indicate that ASP.NET uses the Triple DES symmetrical encryption algorithm to encrypt the ViewState value.</p> <p><machinekey value = "3des" /></p> <p>ViewState security in web field</p> <p>By default, ASP.NET will create a random verification key and store it in local security (LSA) of each server. To verify the ViewState field created on another server, the validationKey of the two servers must be set to the same value. If you want to pass through one of the above methods, you need to provide a ViewState security settings in the web domain configuration, you need to provide a unique, shared authentication key for all servers. The verification key is a random string containing 20 to 64-bit password enhanced bytes, which is represented by 40 to 128 hexadecimal characters. The longer the key, the safer, so it is recommended to use 128 characters (if your computer is supported). E.g:</p> <p><machinekey value = "sha1" validationKey = "</p> <p>F3690E7A3143C185AB1089616A8B4D81FD55DD7A69EEAA3B32A6AE813ECEECD28DEA66A</p> <p>23BEE42193729BD48595EBAFE2C2E765BE77E006330BC3B1392D7C73F "/></p> <p>System.Security.cryptography namespace includes RNGCryptoServiceProvider classes, using this class to generate this string, as shown in the following GenerateCryptoKey.aspx example:</p> <p><% @ Page language = "c #"%></p> <p><% @ Import namespace = "system.security.cryptography"%></p> <p><Html></p> <p><body></p> <p><form runat = "server"></p> <p><H3> Generate Random Admission Key </ h3></p> <p><P></p> <p><ask: radiobuttonlist id = "radiobuttonlist1"</p> <p>Runat = "Server" repeatdirection = "horizontal"></p> <p><asp: listitem value = "40"> 40-byte </ asp: listitem></p> <p><asp: listitem value = "128" SELECTED = "true"> 128-byte </ ask: listItem></p> <p></ asp: radiobuttonlist></p> <p><ask: button id = "button1" runat = "server" οnclick = "generateKey"</p> <p>Text = "Generate Key"></p> <p></ asp: button> </ p></p> <p><P></p> <p><ask: textbox id = "textbox1" runat = "server" textmode = "multiline"</p> <p>Rows = "10" columns = "70" backcolor = "# eeeeee" enableViewState = "false"></p> <p>Copy and paste the result of the result </ asp: textbox> </ p></p> <p></ form></p> <p></ body></p> <p></ Html></p> <p><script runat = server></p> <p>Void GenerateKey (Object Sender, System.EventArgs E)</p> <p>{</p> <p>INT keylength = int32.Pars (radiobuttonlist1.selectedItem.value);</p> <p>/ / Place the user code for the initialization page here</p> <p>Byte [] buff = new byte [keylength / 2];</p> <p>RNGCRYPTOSERVICEPROVIDER RNG = New RNGCRYPTOSERVICEPROVIDER ();</p> <p>/ / The array has been filled with a cipher enhanced random byte</p> <p>RNG.GETBYTES (BUFF);</p> <p>StringBuilder SB = New StringBuilder (Keylength);</p> <p>INT I;</p> <p>For (i = 0; i <buff.length; i ) {</p> <p>Sb.append (String.Format ("{0: X2}", BUFF [I]));</p> <p>}</p> <p>// Paste into the text box, users can copy</p> <p>TextBox1.text = sb.toString ();</p> <p>}</p> <p></ script></p> <p>to sum up</p> <p>ASP.NET ViewState is a new status service that can trace the UI status based on each user. ViewState has no mystery, it just uses an old web programming skill: transfer status in a hidden form field, and applies it directly to the page processing framework. But the effect is very good - simply write and maintain very little code in a web-based form.</p> <p>The user may not always need it, but I think you will find it when you need it, and viewState is a very satisfactory feature that provides many ASP.NET features to page developers.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-98618.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="98618" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.038</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'Nq8X7mSkBEIT_2F441EaQpXSVcMD_2BoBFoZpk2vIHCEcm3C3GfFdRJPZrSWQWCr_2FvBwGa8_2B4ku5ig_2BjJcFDAjF0ag_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>