Hour 2: Understanding 5 ASP.NET State Management Techniques in 5 Hours



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 with. Values can be changed which could not be handled by the application receiving it
  3. We cannot put a large amount of data in a query string, as there is a 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 a query string, there is a 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 to use it: when we want the data to be stored in the query string and it might not consist of legal URL 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=" +

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

Description: 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 in 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 the target page write the code below to access the previous page's control value:

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

Scenario #3: How to keep control view state intact without using CrossPagePostBack.

Solution: Server.Transfer, because we need a workaround, because only a button control implements the iButton interface have this attribute, so in case you don't have any button, you can use the 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 the source page to the target page, and from the target page calls page.previouspage, the life cycle for a source page starts and the Page.load event is fired. Page.IsPostBack property on the source page is true so what happens is your code skips the time-consuming initialization steps. Instead, the control values are restored from the view state. On the other hand, if the Page.IsPostBack property for target page is false, then 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 a scenario where the user clicks the button and validations don't happen for some reason such as client side scripting is not supported. So there should be a 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 the source page needs to know the presence of this query string value and perform the validation. So on the source page we can do 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.

This is the end of your second hour of reading; I hope you enjoyed it.

Click below to contine to the third hour of reading.

Cheers......

Up Next
    Ebook Download
    View all
    Learn
    View all