ASP. NET status management (query strings and cross-page sending back)

Source: Internet
Author: User
ArticleDirectory
    • Query string
    • Query string
    • URL Encoding
    • Cross-page sending back
    • 1. Get specific page information
    • 2. Send cross-page messages in any event handler
    • 4. Cross-page sending and Verification

One of the biggest limits of view status is that it must be closely bound to a specific page. When a user browses from one page to another, the information disappears.. There are several solutions to this problem. The best solution depends on your project requirements.

 

Query string

A common method is to use query strings to send information in a URL. This method is frequently used in search engines.

Http://www.google.ca/search? Q = Organic + gardening

Advantages of string query:

It is lightweightAnd does not increase the burden on the server. Different from cross-page sending back, query stringsIt is easy to transmit the same information between pages..

Query string restrictions:

    1. Information is limited to simple strings,Only valid URL characters are allowed..
    2. UsersEasy to see informationThis is also true for eavesdroppers on the Internet.
    3. Bold users may modify the query string or add new values to it, while yourProgramThese modifications cannot be anticipated or prevented.
    4. Most browsers have limits on the URL string length (usually 1 K-2 K)

However, adding information to a query string is still a useful technique..

 

Query string

There is no collection-based method to help you place information. You need to store the stored information of query strings by yourself.

Int recordid = 10;

Response. Redirect ("Newpage. aspx? Recordid = "+ recordid. tostring ());

Multiple parameters can be sent, separated by symbols.

The receiving page can easily work with query strings. It uses the querystring dictionary set provided by the built-in request object to take values:

String id = requet. querystring ["recordid"];

If the set does not contain the queried key value, the ID is set to null..

The obtained value is always a string, so it is easy to convert to other data types.

 

URL Encoding

A potential problem with string query is the use of characters not allowed in the URL (All characters in the URL must be letters, numbers, and a small number of characters "$-. +! *'(),"). If you are worried that the data to be saved in the query string contains invalid characters, you can use the method provided in the httpserverutility class for encoding.

String productname = "flying carpet ";

Response. Redirect ("Newpage. aspx? Productname = "+Server. urlencode(Productname ));

YouYou can use server. urldecode () to restore the initial value of a string.But this is not required. When the request. querystring set is used, ASP. NET automatically decodes this value.

 

 

 

Cross-page sending back

It's just sending information from one page to another. This technology sounds simple, but it is a potential minefield! Poor use will cause the created page to be tightly coupled and difficult to improve and debug.

 

The infrastructure that supports cross-page sending back is the property postbackurl, which is defined in the ibuttoncontrol interface and appears in button controls (buttons, linkbuttons, imagebutton. You only need to simply set postbackurl to the name of other web forms to use cross-page sending back.

 

Let's look at the following small example:

 
<% @ Page Language = "C #" autoeventwireup = "true" codefile = "crosspage1.aspx. cs" inherits = "chapter06_crosspage1" %>

 
 

<!Doctype Html Public "-// W3C // dtd xhtml 1.0 transitional // en" Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 
 

 
<Html Xmlns= "Http://www.w3.org/1999/xhtml">

<Head Runat= "Server">

 
<Title>Crosspage1</Title>

 
</Head>

 
<Body>

<Form ID= "Form1" Runat= "Server">

 
<Div>

 
<ASP: textbox ID= "Txtfirstname" Runat= "Server"> </ASP: textbox>

 
& Nbsp;<ASP: textbox ID= "Txtlastname" Runat= "Server"> </ASP: textbox>

 
& Nbsp;<ASP: button ID= "Btnsubmit" Runat= "Server" Postbackurl= "Crosspage2.aspx" 

 
Text= "Submit" /> 

 
</Div>

 
</Form>

 
</Body>

 
</Html>

Crosspage2.aspx can interact with objects in crosspage1.aspx through the previouspage attribute:

 
Protected VoidPage_load (ObjectSender, eventargs E)

 
{

 
If(Page. previouspage! =Null)

 
{

 
Lblinfo. Text ="You came from a page titled"+ Previouspage. header. title;

 
}

 
}

 

1. Get specific page information

In the previous example, only members of the page class are obtained. To obtain more details, such as the control value, you must convert previouspage to an appropriate type:

 
Protected VoidPage_load (ObjectSender, eventargs E)

 
{

 
Chapter06_crosspage1 prepage = previouspageAsChapter06_crosspage1;

 
If(Prepage! =Null)

 
{

 
// (Read some infomation from previous page .)

 
}

 
}

Note:

For websites without project files, VS is marked as an error, indicating that it does not have the type information of the Source Page class (such as crosspage1). However, this error disappears after compilation..

 

Even if you have converted the previous page to the correct page type, you still cannot directly access the control value. This is becauseThe control is declared as a protected member.In this case, you can add the property of the encapsulated control variable to the page class to perform the preceding operations:

 
PublicTextbox firstnametextbox

 
{

 
Get {ReturnTxtfirstname ;}

 
}

 
 

PublicTextbox lastnametextbox

 
{

 
Get {ReturnTxtlastname ;}

 
}

But this is not a good method,It displays too many details and allows the target page to freely access any properties of the control.! The best way is to define specific and effective methods or attributes to extract the required information:

 
Public StringFullname

 
{

 
Get {ReturnTxtfirstname. Text + txtlastname. Text ;}

 
}

Now the best status has been reached. The relationship between the two pages is documented and easy to understand. Even if the source page control changes, you only need to modify the fullname attribute. The modification is limited to the crosspage1.aspx page, but does not need to modify the crosspage2.aspx page..

 

2. Send cross-page messages in any event handler

In addition to buttons that implement the ibuttoncontrol interface for cross-page sending, we can also use an overloaded server. Transfer () method to completely send the attempted status information to the target page. Simply add an oreserverfrom parameter with the value true.

 
// If it is true, the system. Web. httprequest. querystring and System. Web. httprequest. Form collections are retained.

 
// If the value is false, the system. Web. httprequest. querystring and System. Web. httprequest. Form collections are cleared.

 
Server. Transfer ("Crosspage2.aspx",True);

In this wayYou canCodeTo any place where the server object can be accessed.).

This technology will cause server redirection, which means there is no additional round-trip to redirect the customer, even if another page has been accessed, the URL in the client browser will not change.

How does one determine whether a button is used for cross-page transfer or the server. Transfer () method for cross-page transfer?

 
Protected VoidPage_load (ObjectSender, eventargs E)

 
{

 
If(Previouspage =Null)

 
{

// Request directly by get or post

 
}

 
Else If(Previouspage. iscrosspagepostback)

 
{

 
// Cross-page callback through the button class

 
}

 
Else

 
{

 
// Return the data across pages through server. Transfer ()

 
}

}

 

3. Ispostback and iscrosspagepostback attributes

Understanding the page. ispostback attribute is very important in cross-page delivery. The ispostback attribute of the Source Page (the page that triggers cross-page delivery) is true. The ispostback attribute of the target page (page for receiving cross-page replies) is false. The advantage of this system is that it means that your initialization code will usually run at this time.

Assume that the first request to crosspage1.aspx uses the following code, it performs some time-consuming initialization work:

 
Protected VoidPage_load (ObjectSender, eventargs E)

 
{

 
If(! Page. ispostback)

 
{

 
// Retrieve some data from a database and display it on the page.

 
}

 
}

Now we assume that the user transfers from page 1 to page 2 through cross-page delivery. As long as the crosspage2.aspx orientation previouspage attribute, the crosspage1.aspx page lifecycle is executed. In this case, the page. Load event of crosspage1.aspx is triggered again. However, if the page. ispostback attribute on crosspage1.aspx is true, your code skips the time-consuming initialization step and the control value is restored from the view status. On the other hand, the ispostback attribute of crosspage2.aspx is false, and all the pages perform the necessary first initialization.

 

In some cases, when a page is not a cross-page return Source Page, you may have the code used to process the first request and all subsequent responses. In this case, you can view the iscrosspagepostback attribute. If a cross-page delivery is triggered on the current page, the value of this attribute is true.

Protected VoidPage_load (ObjectSender, eventargs E)

 
{

 
If(Page. iscrosspagepostback)

 
{

 
// This page triggered a PostBack to crosspage2.aspx.

 
}

 
Else If(Page. ispostback)

 
{

// This page was posted back normally.

 
// Don't do the first-request initialization.

 
}

 
Else

 
{

 
// This is the first request for the page.

 
// Perform all the required initialization.

 
}

 
}

 

4. Cross-page sending and Verification

There are some potential troubles in cross-page delivery verification. If the source page contains a verification control, what will happen when cross-page transmission is used?

Both buttons set causesvalidation to true. Therefore, if you click any button to trigger cross-page sending back, the sending back will be blocked by browser client verification and an error message will appear. In this case, set the attribute enableclientscript of the requiredfieldvalidator verification control to false to simulate that the client does not support JavaScript scripts or malicious customers have avoided client verification. Click any button again to send the page back, and the new page appears.

To avoid this problem, you must check page. isvalid before performing any action to ensure that the source page is valid on the target page. This is a standard precaution for web forms to be verified. The difference is that when the page is invalid, nothing is enough. We often need to take some steps to bring the user back to the original page.:

 
// This code is in target page.

 
Protected VoidPage_load (ObjectSender, eventargs E)

 
{

 
If(Previouspage! =Null)

 
{

 
If(! Previouspage. isvalid)

 
{

 
// Display an error message or just do nothing.

 
// Response. Redirect ("crosspage1.aspx ");

 
}

 
Else

 
{

 
//...

 
}

 
}

 
}

The above code can be improved again. Now, because the page is re-requested (not re-sent), when the user returns to the original page, the error message is not returned. To fix this problem, you can set a flag to let the original page know that the request has been rejected by the target page.

 
Protected VoidPage_load (ObjectSender, eventargs E)

 
{

 
If(Previouspage! =Null)

 
{

 
If(! Previouspage. isvalid)

 
{

 
// Urlreferrer: obtains the URL Information about the client's last request (including many information)

 
// Absolutepath: obtains the absolute path of the URI.

 
Response. Redirect (request. urlreferrer. absolutepath +"? Err = true");

 
}

 
Else

 
{

//...

 
}

 
}

 
}

Now, the original page only needs to check the tags in the query string and perform verification again. The verification will display invalid data information.

 
Protected VoidPage_load (ObjectSender, eventargs E)

 
{

 
If(Request. querystring ["Err"]! =Null)

 
{

Page. Validate ();

 
}

 
}

 

You can also make more improvements to the page. For example, if the user has already filled out a part of a detailed form, it is not good to re-request the page because the user's input is cleared and the user has to re-start. You should write some JavaScript code in the response stream. It uses the browser's rollback function to return to the source page.

 

This example demonstrates that cross-page sending is usually more difficult than developers think. Without careful processing, cross-page re-sending will lead to the generation of tightly coupled pages, which are mutually dependent, making it difficult to modify them in the future.

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.