7

I am trying to send form data from one page to another using C# ASP.Net. I have two pages default.aspx and default2.aspx.Here is the code I have in default.aspx:

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Go" 
    PostBackUrl="~/Default2.aspx" />
<br />

From what I know so far the PostBackUrl is used to set the page in which you want the data to be sent is this correct?

Also how can I retrieve the data that is sent to Default2.aspx?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
user1525474
  • 285
  • 1
  • 4
  • 8

5 Answers5

25

You have a few options, consider

  1. Session state
  2. Query string

Session state

If you are going to send data between pages, you could consider the use of Session State.

ASP.NET session state enables you to store and retrieve values for a user as the user navigates ASP.NET pages in a Web application. HTTP is a stateless protocol. This means that a Web server treats each HTTP request for a page as an independent request. The server retains no knowledge of variable values that were used during previous requests. ASP.NET session state identifies requests from the same browser during a limited time window as a session, and provides a way to persist variable values for the duration of that session. By default, ASP.NET session state is enabled for all ASP.NET applications.

Best of all, it is easy!

Put data in (for example on default1.aspx)

Session["FirstName"] = FirstNameTextBox.Text;
Session["LastName"] = LastNameTextBox.Text;

Get it out (for example on default2.aspx)

string firstname = Session["FirstName"] // value of FirstNameTextBox.Text;
string lastname = Session["LastName"] // value of LastNameTextBox.Text; 

Query string

If you are sending small amounts of data (eg id=4), it may be more practical to use query string variables.

You should explore the use of the query string variables, e.g.

http://www.domain.com?param1=data1&param2=data2

You can then get the data out like

string param1 = Request.QueryString["param1"]; // value will be data1
string param2 = Request.QueryString["param2"]; // value will be data2

You can use something like How do you test your Request.QueryString[] variables? to get the data out.

If you are unfamiliar with querystring variables check out their wikipedia article

Community
  • 1
  • 1
Ian G
  • 29,468
  • 21
  • 78
  • 92
7

Session variables can be useful in this context.

Foe example suppose your textboxes contain login credentials, then save them in sessions so that you can later use them in any other page. Like this:

In Button_Click-

Session["name"]=TextBox1.Text;
Session["pwd"]= TextBox2.Text;

Instead of PostBackUrl="~/Default2.aspx" you can write the following-

//in button click
Server.Transfer("~/Default2.aspx");

In Default2.aspx page load:

string a= Session["name"].ToString();
string b= Session["pwd"].ToString();
Phantomazi
  • 408
  • 6
  • 22
Shiridish
  • 4,942
  • 5
  • 33
  • 64
3

Try this in the Page_Load of Default2.aspx.

 if (PreviousPage != null)
        {
            if (((TextBox)PreviousPage.FindControl("TextBox1")) != null)
            {
                string txtBox1 = ((TextBox)PreviousPage.FindControl("TextBox1")).Text;
                Response.Write(txtBox1);
            }
        }

And yes you are correct, the data from page 1 will be sent to page 2 if you use the PostBackUrl attribute.

MSDN link

Thousand
  • 6,562
  • 3
  • 38
  • 46
  • 1
    I guess he would need to use Server.Transfer – Issa Qandil Oct 07 '12 at 12:22
  • @IssaQandil why would he need that? I just tried this out myself and it works fine. – Thousand Oct 07 '12 at 12:23
  • When you use the Transfer method or use cross-page posting to transfer processing from one ASP.NET page to another, the originating page contains request information that might be required for the destination page. You can use the PreviousPage property to access that information. Taken from this link http://msdn.microsoft.com/en-us/library/system.web.ui.page.previouspage.aspx – Issa Qandil Oct 07 '12 at 12:24
  • I used your code and I seem to be getting a NullPointerException – user1525474 Oct 07 '12 at 12:25
  • @user1525474 where exactly? can you post some more code? It's kinda hard to help with just "i get an error". – Thousand Oct 07 '12 at 12:26
  • @user1525474 try using Server.Transfer replacing Page.Redirect with the same code you are using – Issa Qandil Oct 07 '12 at 12:27
  • I have only added this piece of code in the default2.aspx and I get a nullpointerexception string txtBox1 = ((TextBox)PreviousPage.FindControl("TextBox1")).Text; – user1525474 Oct 07 '12 at 12:28
  • @user1525474 you are testing this by going to default.aspx first right? if you enter some value in a textbox there and then press the button, it should work. If you go directly to default2.aspx you are indeed going to get an error – Thousand Oct 07 '12 at 12:29
  • I have opened default.aspx and aded some data to the textboxes and when I press the button the second page is loaded with the rror – user1525474 Oct 07 '12 at 12:31
  • This is the error: System.NullReferenceException: Object reference not set to an instance of an object. – user1525474 Oct 07 '12 at 12:31
  • Are you sure you are looking for the right control? FindControl("TextBox1")) <-- TextBox1 should be the name of your TextBox on the previous page – Thousand Oct 07 '12 at 12:36
  • well the ID of the control is set to TextBox1 yes but when I check the client ID I get something like this: ctl00$cphBody$TextBox1 is this the reason it's not working? – user1525474 Oct 07 '12 at 12:39
  • i have no idea, i just tried this myself and it's working for me.. if this isn't working maybe you can try out one of the other answers. They should work aswell. – Thousand Oct 07 '12 at 12:51
  • I have posted a question regarding this error an he suggested to sue server.transfer aldo I do not know what that is it may be the caose why it's not working.Is that true? – user1525474 Oct 07 '12 at 13:05
  • I don't know. All i know is that this piece of code is working perfectly fine for me. – Thousand Oct 07 '12 at 13:06
  • Hi I just wanted to tell you that I found why it was not working.My pages are based on a masterpage and in order for it to work I had to add two additional methods Form and another FindControl("for the contentPlaceholderID").This is the expresion that works: text = ((TextBox)Page.PreviousPage.Form.FindControl("cphBody").FindControl("TextBox1")).Text; – user1525474 Oct 07 '12 at 16:11
2

While all the answers here will work some aren't the most efficient. Why would a simple/standard http POST have to invoke (expensive) server-side Sessions?

Your code isn't doing anything special - it is simply POSTing a form to another page. All you need to do to obtain the POSTed data is go through the Request.Form collection.

Prior to the availability to set the PostBackUrl (if memory serves version 1 of asp.net), Server.Transfer and getting references to the previous page was how cross-page POSTing was done/documented. However, with PostBackUrl, things go back to basics, the way it should be - a standard http POST from one resource to another.

Here's a similar SO thread that maybe helpful.

Community
  • 1
  • 1
EdSF
  • 11,753
  • 6
  • 42
  • 83
  • Exactly so by using PostBackUrl you need to go back to the basics – Issa Qandil Oct 08 '12 at 08:20
  • @IssaQandil Yup, ASP.net doesn't introduce anything "special" to the web (but it does wonders for developers). At it's core, it works according to basic principles of `http`. A `Postback` is nothing more than an `http POST` to to the same page. Using `PostBackUrl` just changes the target of the `http POST` to some other resource on the web (that can parse/process POSTed data), ASP.Net or not, same site or not. – EdSF Oct 08 '12 at 14:46
  • That's what i was trying to tell him in his previous question which was discussing the same topic, hopefully he would read your clarification. – Issa Qandil Oct 08 '12 at 17:31
1

another way is to save the data on a database and fetch it back on the other page:

//update
    string query = "UPDATE table SET col = 'a'";
    SqlCommand command = new SqlCommand(query, connection);
    command.ExecuteScalar();

//select
    string query = "SELECT col FROM table";
    SqlCommand command = new SqlCommand(query, connection);
    string value = command.ExecuteScalar();
dizad87
  • 448
  • 4
  • 15