CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
How to Pass Values from One Page to Another in ASP.Net?

By Bala Murugan
Posted On Jul 24,2010
Article Rating:
Be first to rate
this article.
No of Comments: 9
Category: ASP.Net
Print this article.

How to Pass Values from One Page to Another in ASP.Net?

 

It is obvious that any website we develop will have multiple pages and requires a navigation feature to move or browse between pages. At the time of navigation, we will require some data or values to be passed from the source page to destination page in order to do some processing in the destination page. To do this, ASP.Net framework has some handful of features which can assist us in these scenarios.

 

Moving forward, we will see some of the techniques which we can use to pass values from source page to destination page in ASP.Net.

 

Different Ways of Passing Values between Pages

 

Passing Values Using Querystring

This is one of the very common method of sending data from the source page to destination page when using Response.Redirect() method. You can pass values like key=value by separating the target page and querystring with a ? symbol.

 

 For example,

Target.aspx?key=value

 

Multiple values can be separated by & between them.

Target.aspx?key1=value&key2=value

 

In the target page, you can retreive the passed values using the QueryString collection exposed by Request object.

Strinng value = Request.QueryString["val"]

 

Usage

Source.aspx

protected void btnRedirect_Click(object sender, EventArgs e)

    {     

        Response.Redirect("Destination.aspx?val=frompreviouspage");

    }

 

Destination.aspx

 protected void Page_Load(object sender, EventArgs e)

    {       

        Response.Write(Request.QueryString["val"]);     

    }

 

Passing Values Using HttpContext

At times, we use Server.Transfer to redirect the user from one page to another page. In this case, one cannot use querystring because the Server.Transfer will redirect to the target page using the same request in the server i.e. there will not be any roundtrip to the client before redirecting and hence the context of the request in the target page is same as the request in source page.

 

In this scenario, we can use the HttpContext object to pass values from source page to destination page. The HttpContext object exposes an Item collection which will accept name-value pairs. This Item collection can be used to attach a value in source page and retrieve it back from the destination page.

 

Usage

Source.aspx

protected void btnRedirect_Click(object sender, EventArgs e)

    {

        HttpContext _context = HttpContext.Current;

        _context.Items.Add("val", "from previouspage");

       Server.Transfer("Destination.aspx");

    }

Destination.aspx

 protected void Page_Load(object sender, EventArgs e)

    {

        HttpContext _context = HttpContext.Current;

        Response.Write(_context.Items["val"]);

     }

 

Passing Values Using Sessions

This is another option to send values between pages or to put it correctly, persisting values across pages in ASP.Net. You can put whatever values you want to send to the target page in a Session variable and get it back using the same session variable. Remember, using session variable has its own limitation. By default, it uses the ASP.Net process memory and you will have to face the consequence of using it heavily for just passing values from one page to another. Of course, you can configure the ASP.Net to use SQL server or state server to resolve this. Using Session variable is an option and hence it is discussed in this article. Understand the consequence before using approach.

 

To put values in session,

Session["key"] = value

 

To get it back from session in target page,

String val = Session["key"].ToString();

 

Passing Values Using Cookies

This is one another way which you can use to pass values from a source page to destination page in ASP.Net. Remember, like Session it also has its limitation where the cookies are gets stored in clientside and it will be passed to target page. Refer the code below,

 

Usage

Source.aspx

protected void btnRedirect_Click(object sender, EventArgs e)

    {

        HttpCookie cookie = new HttpCookie("PreviousPage");

        cookie.Value = txtValue.Text;      

        Response.Cookies.Add(cookie);

        Response.Redirect("Destination.aspx");      

    }

 

Destination.aspx

protected void Page_Load(object sender, EventArgs e)

    {

        if (Request.Cookies["PreviousPage"] != null)

            Response.Write(Request.Cookies["PreviousPage"].Value);      

    }

 

Refer here to know more about cookies.

 

Passing Values Using Cross Page Postback

Using cross page postback means posting the source page to a different aspx page. By default, all aspx pages will post to itself. You can understand this when you see the action attribute of form tag which will have the value as the same page name. This means, clicking a submit button on the page will post to the same page on the server.  Coming to our subject, you can use this technique to post the values in source page to a destination page using cross page postback.

 

There are multiple ways of implementing it. Some are below,

1.      You can set the action attribute of form tag as Destination page,

<form id="form1" runat="server" action="Destination.aspx">

 

2.      You can use jquery or javascript to chaneg action attibute of form tag to destination page.

<script src="../scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

     <script type="text/javascript">

         $(document).submit(function() {

         $("form").attr("action", "Destination.aspx");

         });

     </script>

 

When using any of these techniques above, you can get source page posted values through the Request.Form collection. For example,

 

Changing action using jquery

<head runat="server">

    <title></title>

    <script src="../scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

     <script type="text/javascript">

         $(document).submit(function() {

         $("form").attr("action", "Destination.aspx");

         });

     </script>

</head>

<body>

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

    <div>

 <asp:TextBox ID="txtValue" runat="server"></asp:TextBox>

<input id="Submit1" type="submit" value="Redirect" />

 </div>

</form>

</body>

</html>

 

Changing the default action in form tag

<head runat="server">

    <title></title>  

</head>

<body>

 <form id="form1" runat="server" action="Destination.aspx">

    <div>

 <asp:TextBox ID="txtValue" runat="server"></asp:TextBox>

<input id="Submit1" type="submit" value="Redirect" />

 </div>

</form>

</body>

</html>

 

To access the value posted in txtValue in destination page when using any of the above 2 approach,

 

Destination.aspx

 protected void Page_Load(object sender, EventArgs e)

    {      

        Response.Write(Request.Form["txtValue"].ToString());

    }

 

The above approach will give ViewStateMac failed error below because the source page viewstate is not valid on destination page.

Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.

 

To resolve this you need to set EnableViewStateMac="false" in @Page directive. Or, you can use the new property of the ASP.Net Button control called PostBackUrl released with ASP.Net 2.0.

To know more about this read Cross Page Post Back in ASP.Net 2.0

 


Passing Values Using @PreviousPageType directive

The new cross page postback feature released with ASP.Net 2.0 gave a new property on Page object called PreviousPage which provided access to the source or parent page. You can now declare a public property in the source page and include @PreviousPageType directive in the destination page to re-declare the source page controls or properties in the destination page. You should use Server.Transfer to redirect to the target page in order to access the source page property using PreviousPage property. Refer the code below,

Source.aspx.cs

public partial class PreviousPage_Source : System.Web.UI.Page

{

    public string GetText

    {

        get

        {

            return txtValue.Text;

        }

    }

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }

    protected void btnRedirect_Click(object sender, EventArgs e)

    {       

       Server.Transfer("Destination.aspx");

    }

}

 

Destination.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Destination.aspx.cs" Inherits="PreviousPage_Destination" %>

<%@ PreviousPageType VirtualPath="~/Transfer/Source.aspx" %>

 

Destination.aspx.cs

protected void Page_Load(object sender, EventArgs e)

    {       

        Response.Write(PreviousPage.GetText);

    }

 

Reference

http://msdn.microsoft.com/en-us/library/6c3yckfw.aspx

 

Conclusion

Thus, we have seen some of the ways through which we can pass values between pages. As discussed in this article, each has its own advantages and disadvantages.

1.      Don’t use Querystring to send protected information as it is seen by everyone and cached over places. You can prevent this or use proper encode/decode mechanisms.

2.      Don’t store secured information in cookies as it gets stored in clientside. Try setting expiration time, use non-persistent cookies or don’t use it.

Using HttpContext is a good way and understand it works only with Server.Transfer. Also Session variable are one way of persisting secured information’s across pages but again it has also some trade-offs discussed above. In general, take an extra care when sending the values from one page to another. Understand the risks and do a proper analysis of your requirement and sensitivity of the data before deciding the approaches above.

 

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
Usefull
Thank You
data passing
Sir i need to pass list items id to another page how can i do that
trghff
thtrh
mr
very clear and straight forward. Thanks for the post
Using PAYPAL In my ASP.NET
Hi sir am developing one Asp.net website,
I want to sell my site using PAYPAL,
can you tell me the process,I have a one Registration page I want to place paypal in that page now i am continue to sell my site,
pls help me

Just like you are using in your site
nice
nice article
Good Article
very helpful for .net devolopers
Nice article
Its a nice informative article. You bit forgot to mention about hidden fields like ; <input type= "hidden"/>

We can also use the same to pass values.
Thank you , it was wonderful!
Hi,

Thanks. The articles is concise and written in simple language. With just enough depth for an introduction or in my case for a recap.
Also the conclusion and additional points mentioned are very pertinent.

A superb article. Keep posting more!