Passing Values from One Page to Another Page – ASP.NET


Passing parameters from one page to another is a very common task in Web development. Granted, its importance and frequency has faded a bit with ASP.NET’s inherent preference for postback forms, but
regardless, there are still many situations in which you need to pass data from one Web page to another.

There are three widely used methods of passing values from one page to another in ASP.NET
Main

1. Using Query String

We usually pass value through query string of the page and then this value is pulled from Request object in another page.

FirstForm.aspx.cs
—————–
Response.Redirect(“SecondForm.aspx?Parameter=” + TextBox1.Text);

SecondForm.aspx.cs
——————
TextBox1.Text = Request. QueryString[“Parameter”].ToString();

This is the most reliable way when you are passing integer kind of value or other short parameters.More advance in this method if you are using any special characters in the value while passing it through query string, you must encode the value before passing it to next page. So our code snippet of will be something like this:

FirstForm.aspx.cs
—————
Response.Redirect(“SecondForm.aspx?Parameter=” + Server.UrlEncode(TextBox1.Text));

SecondForm.aspx.cs
—————–
TextBox1.Text = Server.UrlDecode(Request.QueryString[“Parameter”].ToString());

2. Passing value through context object

Passing value through context object is another widely used method.

FirstForm.aspx.cs
—————
TextBox1.Text = this.Context.Items[“Parameter”].ToString();

SecondForm.aspx.cs
——————
this.Context.Items[“Parameter”] = TextBox1.Text;
Server.Transfer(“SecondForm.aspx”, true);

Note that we are navigating to another page using Server.Transfer instead of Response.Redirect.Some of us also use Session object to pass values. In that method, value is store in Session object and then later pulled out from Session object in Second page.

3. Posting form to another page instead of PostBack

Third method of passing value by posting page to another form. Here is the example of that:

FirstForm.aspx.cs
—————
private void Page_Load(object sender, System.EventArgs e)
{
buttonSubmit.Attributes.Add(“onclick”, “return PostPage();”);
}

And we create a javascript function to post the form.

SecondForm.aspx.cs
—————–

function PostPage()
{
document.Form1.action = “SecondForm.aspx”;
document.Form1.method = “POST”;
document.Form1.submit();
}
TextBox1.Text = Request.Form[“TextBox1”].ToString();

Here we are posting the form to another page instead of itself. You might get viewstate invalid or error in second page using this method. To handle this error is to put EnableViewStateMac=false

4. Another method is by adding PostBackURL property of control for cross page post back

In ASP.NET 2.0, Microsoft has solved this problem by adding PostBackURL property of control for cross page post back. Implementation is a matter of setting one property of control and you are done.

FirstForm.aspx.cs
————–
<asp:Button id=buttonPassValue style=”Z-INDEX: 102″ runat=”server” Text=”Button”         PostBackUrl=”~/SecondForm.aspx”></asp:Button>

SecondForm.aspx.cs
—————–
TextBox1.Text = Request.Form[“TextBox1”].ToString();

In above example, we are assigning PostBackUrl property of the button we can determine the page to which it will post instead of itself. In next page, we can access all controls of the previous page using Request object.

You can also use PreviousPage class to access controls of previous page instead of using classic Request object.

SecondForm.aspx
—————
TextBox textBoxTemp = (TextBox) PreviousPage.FindControl(“TextBox1”);
TextBox1.Text = textBoxTemp.Text;

As you have noticed, this is also a simple and clean implementation of passing value between pages.
Conclusion Passing values between pages is another common task accomplishes in web based development. As we have discussed many of mechanisms above, I prefer and recommend to use Query String then other
methods for its clean and simple implementation as long as your parameter doesnt have security concern.

Reference :

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

46 thoughts on “Passing Values from One Page to Another Page – ASP.NET

  1. hi sir…….thanx for u r post i have one problem i m usinf form authontication to restrict user….after login user will redirect to idex page but i want to pass username & user status to index page how do i pass this values..plz help me

    1. Hi Shubhangi,

      There are some of options :
      1)you can pass values using querystring (pass username & status with querystring)
      Note : if you do not want to allow that user see those values – you can encrypt & decrypt querystring.

      2) you can also store those values in session & fetch it on index page once login process succeed.

      Hope this will help !!! Let me know if you have any more concern..

  2. hello sir,
    how to display video in facebook using embed code
    when i pest embed code in Post Wall text box then not display video like (open http://campuin.com) open user profile and post embed code in wall system here display video… how it possible in FaceBook

      1. Hi Krishna, on FB i dont think that is possible, but still i m not sure about it. you should check it out.

  3. hi Sandeep

    What’s better, a hidden field or viewstate?
    what is real differents between them ??
    i use Viewstate for store “HostID” but never use hidden field
    which is better??

    1. It depends on the scenarios in which you want to use them.
      If you need security Viewstate is more preferable over hiddenfield. Hope this will help !!!

    1. Hi Liaw, Is this secret no? if yes then pass it thru session/context object. Otherwise you can pass them thru QueryString also. Let me know if any other concern is there.

      Regards,
      Sandeep Ramani

      1. Thank first Sandeep.. it works… but i got another question.. vip member can display vip button and normal button while normal member just can display normal button.. how can i do it? because vip and normal member also display both button…

    2. Hi Liaw, If you are displaying button based on User role or any other conditions than only thing you need to check which button is displayed. if anyone or both button is displayed as per your conditions/user role just fetch the values you want to pass accordingly and pass them as per method you are using i.e querystring/session/context etc…

      Hope this will help

      Regards,
      Sandeep Ramani

    1. Hi Silambarsan, you can pass text in textbox using QueryString/Context/Session methods. I have also explained in my article how to do so…if u still have any doubt in it. let me know your concerns.

      Regards,
      Sandeep Ramani

  4. Pingback: Website Design
  5. Pingback: smart shop
    1. Hi Sagar, for multiple value passing, you can use session and passing custom object inside session is the good way. Hope you are getting what i am trying to convey.

      Regards,
      sandeep

  6. i have multiple check box in different- 2 cell lust like in one row four cell and value like part no, item, image and check box i want to select check box then click button then all value go to another page text box in asp.net how to do it …plz send me any one code my email rajeshk99@gmail.com

  7. sir, in my project i displayed a list of function halls using link button for each function hall. i want to display the text of the linkbutton on the top of the navigated page…….. pls tell me

  8. sir , i want to post a message with a smaill photo to another page like as we are doing in facebook when we posted a comment in a friends status our comment as well as photo is seems …..

  9. i hav taken two listbox and a button and a checkbox. and i have puted two names(deb and sumanta) in the first listbox. now i want that whenever a user click on the deb and click the button at that time name, ph.no will appear on 2nd listbox.
    if a user again choose deb and tick the check box then name ,ph.no and address will appear on the 2nd listbox…

  10. Your blog is very help full,
    I have one requirement like this
    I have a table CUSTOMER in that CUSTID,NAME,URL columns is thier
    CUSTID NAME URL
    1 asp http://www.asp.net
    2 weblog http://www.weblogs.asp.net
    3 google http://www.google.com

    My question is I opening perticular url based on CUSTID

    I am Passing parameter Like http://www.Example.com?CUSTID=1 That

    corressponding URL data(Ex:www.asp.net) It will open directly in browser

    using asp.net……..
    plz help me ………..
    Thank you,
    anil

  11. With havin so much content do you ever run into any issues of plagorism or copyright violation?

    My site has a lot of unique content I’ve either authored myself or outsourced but it looks like a lot of it is popping it up all over the internet without my permission. Do you know any methods to help reduce content from being ripped off? I’d really appreciate it.

  12. hai, this s athiq,,,,my question is how to Post-Data-from-One-form-to-other-form-using-CrossPage-techiniuqe-in-ASPNET-2 along with c# code.

  13. hai,,this s athiq,,,i create a design for mail service using ASP.Net,,in that i need to retrieve the mail body data from database.

  14. i have some textboxes.. when ‘preview’ button is clicked it goes to another page, preview.aspx which contains an html template.. i need to replace the textbox entered values inside the template.. how will i code it using asp.net? The html template is

    preview.aspx …..

        From:  
    [mg-from]
        To:    
    [mg-to]
        Subject:
    [mg-subject]

    need to replace [mg-from] with txtfrom.text of the first page……how will i code it using asp.net ……. pls help me ….

  15. Attractive part of content. I just stumbled upon your
    blog and in accession capital to claim that I get in
    fact enjoyed account your blog posts. Anyway I will be subscribing on your augment and even I success you get entry to consistently quickly.

  16. Do you mind if I quote a couple of your posts as long as I provide credit and sources back to your blog?

    My blog is in the very same area of interest as yours and my users would
    definitely benefit from a lot of the information you present here.

    Please let me know if this ok with you. Regards!

  17. Thank you a bunch for sharing this with all folks you really
    recognise what you are speaking about! Bookmarked.
    Please also visit my site =). We could have a hyperlink
    trade arrangement among us

  18. First off I want to say fantastic blog! I had a quick question that I’d like to ask if you don’t mind.
    I was curious to find out how you center yourself and clear your head prior to writing.
    I have had a hard time clearing my mind
    in getting my thoughts out there. I truly do enjoy writing but it just seems like the first 10 to 15 minutes are usually lost
    just trying to figure out how to begin. Any suggestions or tips?
    Thanks!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s