Regain web development-ASP. NET review

Source: Internet
Author: User

There is too much knowledge about ASP. NET. Only some questions are listed here for your consideration and some knowledge points will be added at any time.

Page Lifecycle

For the page lifecycle of Asp.net, first look at the two pictures I added to my favorites. The first picture is a bit defective, and the second picture has less information, but it can be illustrated with the two pictures.

 

I would like to raise a few more important questions:

Where is the page sound lifecycle in the entire HTTP request?

What is the event execution sequence of the control?

When does the widget bind data?

When does the trackviewstate of viewstate start?

When will the viewstate value be loaded?

How does the control catch up with the lifecycle? Only for dynamically created controls?

Server Control

I also asked a few questions about server controls for my own consideration (answer)

What is a control tree?

What are the differences between HTML controls, HTML server controls, and Asp.net web server controls?

How does ASP. NET handle runat = "server "?

How does one handle The onclick of a server control?

What are the forwarding events of nested controls?

Viewstate and return value (postdata)

As shown in the following example: When a page is loaded, we bind dropdownlist. When a button is not bound to any processing event, we only want to send the page back when you click it:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="test3.aspx.cs" Inherits="test.test3" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Protected void page_load (Object sender, eventargs e) {If (! Ispostback) {This. dropdownlist1.datasource = querydatabase (); this. dropdownlist1.databind () ;}} private list <string> querydatabase () {list <string> result = new list <string> (); result. add ("Beijing"); result. add ("Shanghai"); result. add ("Shenzhen"); result. add ("Anhui"); result. add ("Guangdong"); return result ;}

When running this page, we find that everything runs normally. After each sending back, the dropdownlist data still exists and the last selected value is displayed. Look at our code if (! Ispostback) this line, which indicates that we only bound the dropdownlist when loading the page for the first time. The reason why everything works is that it is not hard to understand the viewstate introduction in front of the page load because trackviewstate () it has been started. At this time, the data in dropdownlist has been saved between the backhaul through serialization and deserialization, as well as the loadviewstate () and saveviwstate () methods. However, if the data bound to this drop-down list is large, a large amount of _ viewstate information will be carried in every response to the page, which affects the speed with low bandwidth. So I want to avoid overhead by disabling the enableviewstate attribute of dropdownlist, but re-Binding data every time (to measure the performance between the two methods, of course, it is not feasible to bind data only when loading the page for the first time as above. Remove if (! Ispostback )! It seems okay, but one problem is that the drop-down list after each sending back is no longer the last selected value. Why? Many people, including those who previously thought it was because we disabled the viewstate of dropdownlist, let's rebind data in onload each time and set the enableviewstate attribute to true. (to do this in the real environment, this will cause double performance loss ). The problem still exists. After each sending back, the list is displayed as "Beijing", no matter what you have selected. Why? Some other things are not saved by viewstate during page return, but by another key-value pair, which is called the return value (postdata ), by default, the POST request is returned. We can change it to the get method and add method = "get" to the form ":

<form id="form1" runat="server" method="get">

We can find that the URL of the browser has changed. The reason why a lot like = is due to encryption.

http://localhost:5738/test3.aspx?__VIEWSTATE=%2FwEPDwUJMzkwNTA5NDc2D2QWAgIDD2QWAgIBDxAPFgIeC18hRGF0YUJvdW5kZ2QQFQUG5YyX5LqsBuS4iua1twbmt7HlnLMG5a6J5b69BuW5v%2BS4nBUFBuWMl%2BS6rAbkuIrmtbcG5rex5ZyzBuWuieW%2BvQblub%2FkuJwUKwMFZ2dnZ2dkZGSNKet80L43lwcKiYK8hHkQraKPiqkyOu7uuQGF0c73yQ%3D%3D&__EVENTVALIDATION=%2FwEWBwLM2oqDDQK0tbT8CwK7n8DiBQLS0NCwBQK6hPj0CgLMv%2FT7CwKM54rGBrqd0YO1IQK9DNW9Us7zGuPCFrnql5ep1WBFw2V1eKTq&DropDownList1=%E6%B7%B1%E5%9C%B3&Button1=PostBack

So why can't we get the value of sending back when we bind the dropdownlist in onload? Let's look back at the page's lifecycle chart. The method for processing the returned data (postdata) is processpostdata () called twice, one before the page load event, once after load. For static controls (as in our code), loading the return data to the control will only happen in the first processpostdata, so the reason why the drop-down list will forget the last selection is that load occurs after processpostdata () and when the data is loaded and sent back, the dropdownlist has no listitem. For controls dynamically created in onload, there is another opportunity for procsspostdata, so the solution to the problem above is to bind the data before processpostdata (), such as oninit:

Protected void page_load (Object sender, eventargs e) {// If (! Ispostback) // {// This. dropdownlist1.datasource = querydatabase (); // This. dropdownlist1.databind (); //} private list <string> querydatabase () {list <string> result = new list <string> (); result. add ("Beijing"); result. add ("Shanghai"); result. add ("Shenzhen"); result. add ("Anhui"); result. add ("Guangdong"); return result;} protected override void oninit (eventargs e) {This. dropdownlist1.datasource = querydatabase (); this. dropdownlist1.databind (); base. oninit (E );}

Whether to re-bind the control or use viewstate for higher performance or more satisfying scenarios depends on the specific situation.

Control "Catch Up"

Although the above example solves our problem: the performance loss caused by misuse of viewstate and dropdownlist forget the previous choice. However, by binding data in advance and disabling the viewstate of the control, another problem occurs because disabling the enableviewstate attribute of dropdownlist will make our selectedindexchanged unable to be triggered.Make sure to set the autopostback attribute of dropdownlist to true. Otherwise, it will not be sent back immediately. Wait until the next submission and be aware of the existence of postdata. Do not interfere with your judgment.I found a strange phenomenon. Let's look at the following example:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="test3.aspx.cs" Inherits="test.test3" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Protected void page_load (Object sender, eventargs e) {// If (! Ispostback) // {// This. dropdownlist1.datasource = querydatabase (); // This. dropdownlist1.databind (); //} private list <string> querydatabase () {list <string> result = new list <string> (); result. add ("Anhui"); result. add ("Beijing"); result. add ("Shanghai"); result. add ("Shenzhen"); result. add ("Guangdong"); return result;} protected override void oninit (eventargs e) {This. dropdownlist1.datasource = querydatabase (); this. dropdownlist1.databind (); base. oninit (E);} protected void dropdownlistincluselectedindexchanged (Object sender, eventargs e) {// It indicates that selecteditem is not returned through viewstate // If (dropdownlist1.selecteditem. TEXT = "Shanghai") // {// response. write ("you have selected Shanghai"); //} response. write (dropdownlist1.text );}

Added a selectedindexchanged event to dropdwonlist in the previous example. In the response time function, the text in the current drop-down box is output to the page. Like the above, the viewstate of dropdownlist is disabled, according to my expectation, the page does not respond when selecting the drop-down box, but the result is that other pages can still be output except the first element in the selection list, when the enableviewstate attribute of dropdownlist is set to true, the result is the same as expected. Is it true that the first element in the drop-down list is returned through viewstate and the rest are returned through postdata ?? There must be another reason for this. For the moment, no matter whether the first element and the expected result are selected when viewstate is disabledReference. To put it bluntly: Since the method in the previous example cannot solve the impact of disabling viewstate, is there a perfect solution, the beauty of the two worlds is that we can avoid unnecessary increases in viewstate when initializing the drop-down list data, and keep viewstate when we need it? Yes! This method is to dynamically create a control. Before explaining why, let's take a look at how to do this. First Delete the dropdownlist added statically in the code, and then dynamically create it in oninit:

Dropdownlist refdl = NULL; protected void page_load (Object sender, eventargs e) {} private list <string> querydatabase () {list <string> result = new list <string> (); result. add ("Anhui"); result. add ("Beijing"); result. add ("Shanghai"); result. add ("Shenzhen"); result. add ("Guangdong"); return result;} protected override void oninit (eventargs e) {dropdownlist dropdownlist1 = new dropdownlist (); dropdownlist1.datasource = querydatabase (); dropdownlist1.databind (); // save reference refdl = dropdownlist1; // set Automatic sending back to true dropdownlist1.autopostback = true; // The binding event dropdownlist1.selectedindexchanged + = new eventhandler (handler) That must be displayed in the dynamically created control ); this. form. controls. add (dropdownlist1); base. oninit (E);} protected void dropdownlistincluselectedindexchanged (Object sender, eventargs e) {// It indicates that selecteditem is not returned through viewstate // If (dropdownlist1.selecteditem. TEXT = "Shanghai") // {// response. write ("you have selected Shanghai"); //} response. write (refdl. text );}}

Why are there two problems involved?

  1. When does a dynamically created control start to track its viewstate?
  2. What should I do when the status of the dynamically created control lags behind the page lifecycle?

We can dynamically create controls at any stage of the page lifecycle. At the same time, we know from the first figure above that trackviewstate () is completed in the oninit stage, the oninit of the control is recursively completed before the oninit of the page, so in the oninit of the page, or even in extreme cases, a control is dynamically created in the onprerender stage of the page, will this control miss its own trackviewstate? The key lies in the above this. form. controls. add () method in add (dropdownlist1); I am also studying this method and its internal details, but in general this method checks the stage of the control, there will be"Catch up"The process will execute some methods of this control manager, of course, also include trackviewstate (), but it seems that some private methods will also be ignored, because this catch-up process occurs in add () therefore, the previously bound data will not be treated as "dirty data" or added to viewstate. Meanwhile, events such as selectedindexchange will still be triggered normally due to catch-up.

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.