Understanding ASP.NET State management techniques-Part II

No.of Views847
Bookmarked1 times
Downloads 
Votes0
By  Vishal Nayan   On  26 Jun 2011 06:06:01
Tag : ASP.NET , State Management
In this part of the series article going to explain, how to manage state with query string in asp.net.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

In this part of the series article going to explain, how to manage state with query string in asp.net. Before you read this article, you could read other parts of this series below,

http://www.codegain.com/articles/aspnet/statemanagement/understanding-aspnet-state-management-techniques-part-iii.aspx

http://www.codegain.com/articles/aspnet/statemanagement/understanding-aspnet-state-management-techniques-part-iv.aspx

http://www.codegain.com/articles/aspnet/statemanagement/understanding-aspnet-state-management-techniques-part-v.aspx

Query String

Points to remember: Benefits

1)    Used for passing information using a query string in the URL
2)    The query string is the portion of the URL after the question mark
3)    Query strings are lightweight and don’t exert any kind of burden on the server.
4)    Best suited in e-Commerce scenario

Points to remember: Disadvantages

1)    They can only contain simple string and they should only contain URL pre-defined accepted characters.
2)    Information is visible and can be tampered. Values can be changed which could not be handled by the application at receiving it
3)    We cannot put large amount of data in query string, as there is size limitation enforced by different browsers, usually from 1 to 2 Kb.

How to send value in query string

Response.Redirect("QueryStringRecipient.aspx" + "?Version=" +
                ((Control)sender).ID);

How to receive value from query string

lblDate.Text = "The time is now:<br>" + DateTime.Now.ToString();
        switch (Request.QueryString["Version"])
        {
            case "cmdLarge":
                lblDate.Font.Size = FontUnit.XLarge;
                break;
            case "cmdNormal":
                lblDate.Font.Size = FontUnit.Large;
                break;
            case "cmdSmall":
                lblDate.Font.Size = FontUnit.Small;
                break;
        }

What is URL encoding?

In query string, there is limitation in allowing valid characters. With URL encoding, special characters are replaced by escaped character sequences starting with the percent sign (%), followed by a two-digit hexadecimal representation.

When you have to use URL Encodinng?

when we want that the data should store in the query string may not consist of URL legal characters, you should use URL encoding.

These special characters have special meaning,

1)    (&) is used to separate multiple query string parameters,
2)    (+) is an alternate way to represent a space
3)    (#) is used to point to a specific bookmark in a web page.

Example:

string productName = "Apple iPad";
        Response.Redirect("newpage.aspx?productName=" + Server.UrlEncode(productName));

Here we have used method UrlEncode from HttpServerUtility class. URL encloding here we are encoding a string of arbitrary data for use in the query string. This replaces all the non legal characters with escaped character sequences.

HttpServerUtility.UrlDecode()
method can be used to  return a URL-encoded string to its initial value.

Cross Page Posting

Till here we learned that page postbacks to themselves, and when they do it send back the current controls in the form for that page which also includes content of hidden variables value.

How it works

PostBackUrl property of button support cross page post backs. When the user clicks the button, the page will be posted to that new URL with the values from all the input controls on the current page.

Scenario #1: How to Set CrossPostBack attribute

<asp:Button runat="server" ID="cmdPost" PostBackUrl="CrossPageTarget.aspx" 
            Text="Cross-Page Postback"  />

Scenario #2: How to get source page info on target page.

In CrossPageTarget.aspx, the page can interact with the CrossPageSpurce.aspx objects using the Page.PreviousPage property.

if (Page.PreviousPage != null)
        {
            lblInfo.Text = "You came from a page titled " +
            PreviousPage.Header.Title;
        }

But if we are interested into more specific details, such as control values, you need to cast the PreviousPage reference to the appropriate type.

CrossPageSource prevPage = PreviousPage as CrossPageSource;

Just by casting the previous page to the appropriate page type, we still won’t be able to directly access the control values. That’s because the controls are declared as protected members. You can handle this by adding properties to the page class that wrap the control variables

In Source page, create a property like this;

public string TextBoxContent
    {
        get { return txt1.Text; }
    }

And in target page write below code to access previous page control value

if (prevPage != null)
                {
                    lbl.Text += "You typed in this: " + prevPage.TextBoxContent + "<br />";
                }

Scenario #3: How to keep control view state inact without using CrossPagePostBack.
Solution; Server.Transfer , because we need some work around , because only button control implements iButton iterface have this attribute , so in case you don’t have any button  , you can use server.tranfer overloaded method.

Server.Transfer("CrossPageTarget.aspx", true);

Scenario #4:  How to check between a cross-page post that’s initiated directly through a button and the Server.Transfer() method

if (PreviousPage.IsCrossPagePostBack)
                {
                    lbl.Text += "The page was posted directly";
                }
                else
                {
                    lbl.Text += "You used Server.Transfer()";
                }

Scenario #5: How Page.IsPostBack work in Cross Page PostBack.

For the source page (the one that triggered the cross-page postback), the IsPostBack property is true. For the destination page (the one that’s receiving the postback), the IsPostBack property is false.

How it works: once we navigate from source page to target page, and from target page calls page.previouspage , life cycle for source page starts and Page.load event is fired. Page.IsPostBack property on source page is true so what happens is your code skips the time-consuming initialization
steps. Instead, the control values are restored from view state.  On the other hand, the Page.IsPostBack property for target page is false, so this page performs the necessary first-time
Initialization.

if (IsCrossPagePostBack)
        {
            // This page triggered a postback to CrossPage2.aspx.
            // Don't perform time-consuming initialization unless it affects
            // the properties that the target page will read.
        }
        else if (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.
        }

Scenario #6: How Validation controls works in Cross Page Postings.
We are looking at scenario where user click the button and validations doesn’t happens for any reason say client side scripting is not supported. So there should be an way out by which we can test it from target page.

if (Page.PreviousPage != null)
        {
            if (!PreviousPage.IsValid)
            {
                Response.Redirect(Request.UrlReferrer.AbsolutePath + "?err=true");
            }
            else
            {

		}

So now source page need to know presence of this query string value and perform the validation. So on source page we can something like this;

protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["err"] != null)
            Page.Validate();
    }

To test this set RequiredFieldValidator.EnableClientScript property to false.
Thank you for reading Hope you enjoyed it.
 

 
Sign Up to vote for this article
 
About Author
 
Vishal Nayan
Occupation-Software Engineer
Company-
Member Type-Junior
Location-India
Joined date-02 Apr 2011
Home Page-
Blog Page-http://vishalnayan.wordpress.com
Vishal is a seasoned professional with hand on experience on Microsoft technologies. He always look for challenging assignment that allows him to learn newer technologies while utilizing his experience of project development and software engineering ethics. In spare time vishal can be found reading business and political personalities, acts as critics at columnist , writing poetries, bird watching , singing ,cooking. He have strong interests in Indian business and political arena and want to be an active one someday. He is also a part-time trainer on framework , WCF and Silverlight. reach him at vishalnayan@gmail.com
 
 
Other popularSectionarticles
    It is a storage mechanism that is accessible from all pages requested by a single Web browser session. Therefore, you can use session state to store user-specific information. A session is defined as the period of time that a unique user interacts with a Web application. Active Server Pages (ASP) developers who wish to retain data for unique user sessions can use an intrinsic feature known as session state.
    Published Date : 02/Jun/2011
    It store global objects that can be accessed by any client.It supports the same types what session state support which are of type objects, retains information on the server, and uses the same dictionary-based syntax. Application state is based on the System.Web.HttpApplicationState class, which is provided in all web pages through the built-in Application object.
    Published Date : 09/May/2011
    Http protocol is stateless, so we need to maintain state on Client side or Server side. For this time I am going to discuss about the maintaining state on Server Side with one programming practice.
    Published Date : 10/Jan/2011
    Now web application framework, no matter how advanced, can change that HTTP is a stateless protocol. So inherently we should also forget our users, but unfortunately we cannot.ASP.Net Framework provides us features by which we can maintain states of your users.
    Published Date : 26/Jun/2010
    There is Lots of ways and Techniques Are available to Manage you State on Web in Aspnet
    Published Date : 06/May/2010
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top