[Repost] ASP.NET ViewState

xiaoxiao2021-03-06  24

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 not status of the UI status Web for maintenance page, and 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's working principle 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. Let's make full use of ViewStateViewState to provide a magical way to the status of the transmission tracking control, as it does not use server resources, not timeout, and applies 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 ("Sortorder") = "DESC"

'Read Dim Sortorder AS String = CSTR (ViewState ("Sortorder") from ViewState

[C #] // Save in ViewState ["Sortorder"] = "DESC";

/ / Read string sortorder = (string) ViewState ["Sortorder"] from ViewState;

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"%> ViewState / Title> </ head> <body> <form runat = "Server for page UI status values "> <H3> Store non-control status in ViewState </ h3> <p> This example stores the current sort order of a column of static data in ViewState. <br> Click the link in the column header to select the data according to this field. <br> Click the link again to sort in the reverse order. <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" forcolor = "white" backcolor = "# 006699> </ headerstyle> </ asp: datagrid> </ p> </ form> < / body> </ html> <script runat = "server"> 'Tracking Sortfield Properties in ViewState Property Sortfield () AS String</p> <p>Getdim o as object = viewState ("sortfield") if o is nothing thereturn string.emptyEND ifreturn CSTR (o) End Get</p> <p>Set (Value As String) if Value = Sortfield Ten 'is the same as the current sort file, switching sorting direction sortascending = not sortascendingend IFviewState ("sortfield") = valueend set</p> <p>End Property</p> <p>'Tracking Sortascending Properties in ViewState Property Sortascending () AS Boolean</p> <p>Getdim o as object = viewState ("sortascending") IF o is nothing thereturn truend ifreturn CBOOL (O) End Get</p> <p>Set (Value As Boolean) ViewState ("Sortascending" = ValueEnd 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 thenbindgrid () endiff</p> <p>End Sub</p> <p>Sub bindgrid ()</p> <p>'Get Data DIM DS As New Dataset () DS.Readxml (Server.MAppath ("TestData.xml")) DIM DV AS New DataView (ds.tables (0))</p> <p>'Apply Sorting Filters and Directions DV.Sort = Sortfieldif Not Sortascending Thendv.Sort = "DESC" End IF</p> <p>'Binding Grid DataGrid1.datasource = DVDataGrid1.database ()</p> <p>End Sub</p> <p>Private Sub Sortgrid (Sender As Object, E AS DataGridSortCommandeventAndargs) DataGrid1.currentPageIndex = 0Sortfield = E.SortexpressionBindGrid () end SUB</p> <p></ script></p> <p>[C #]% @ page language = "c #"%> <% @ import name "%> <html> <head> <title> for page UI status value for ViewState </ Title> </ Head> <body> <form runat = "server"> <h3> Store non-control status </ h3> <p> in ViewState This example stores the current sort order of a column of static data in ViewState. <br> Click the link in the column header to select the data according to this field. <br> Click the link again to sort in the reverse order. <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" forcolor = "white" backcolor = "# 006699> </ headerstyle> </ asp: datagrid> </ p> </ form> < / body> </ html> <script runat = "server"></p> <p>// Track Sortfield attributes in ViewState String Sortfield {</p> <p>Get {Object O = ViewState ["sortfield"]; if (o == null) {return string.empty;} return (string) o;}</p> <p>Set {if (value == sortfield) {// The same as the current sort file, switch sorting direction sortascending =! sortascending;} ViewState ["sortfield"] = value;}} // Track the sortascending attribute bool sortascending {</p> <p>Get {Object O = ViewState ["Sortascending"]; if (o == null) {Return True;} Return (BOOL) O;</p> <p>Set {ViewState ["Sortascending"] = value;}}</p> <p>Void Page_Load (Object Sender, Eventargs E) {</p> <p>IF (! page.ispostback) {bindgrid ();}}</p> <p>Void bindgrid () {</p> <p>// Get data dataset ds = new dataset (); ds.readxml (server.mappath ("testdata.xml");</p> <p>DataView DV = New DataView (ds.tables [0]);</p> <p>// Applied sort filter and direction DV.Sort = sortfield; if (! Sortascending) {dv.sort = "desc";</p> <p>// Bind grid DataGrid1.datasource = DV; DataGrid1.database ();</p> <p>Void Sortgrid (Object Sender, DataGridSortCommandeventEventArgs E) {</p> <p>DataGrid1.currentpageIndex = 0; sortfield = e.sortexpression; bindgrid ();}</p> <p></ script></p> <p>The following is the code referenced by the TestData.xml referenced in the above two code segments:</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-41896.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="41896" 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.033</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 = 'PdrOExhmHlDayD8TZdgi1rP4QYEPYUKyXJ1xZTxGMf8UqnG74NKVcGOAUw9j9P7DAaOK5WSaDG7KsGIg'; 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>