Monday, August 23, 2010

Cross page posting, Submit Form and Server.Transfer methods for data transfer

Cross page posting in ASP.NET

First of all we need to set the PostBackUrl property
of the Button we are gonna use for postback, to the page where we need to redirect, in our case it's Default2.aspx
to retrieve the value of a textbox from previous page in Default2.aspx page
we need to use FindControl method to find the textbox control of previous page

TextBox txtName = (TextBox)PreviousPage.FindControl("txtUserName"));

lblName.text = txtName.Text.ToString()
;

Submit Form Method to post data and retrieve on another page in ASP.NET

To start with simplest method we can write code like this

<form id="form1" method="post"
action="Default2.aspx">
Data <input type="text"
name="Data" size="20"><br>

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

And to retrieve it on the posted page
lblValue.Text = Request.Form["Data"];


asp.net does not support post method with runat="Server" attribute,
for this we will have to use javascript

<form id="Form1" method="post"
runat="server">
<asp:TextBox ID="txtData" runat="server">
</asp:TextBox>
</form>

<form name="FormSubmit" action="Default2.aspx"
method="post">
<input id="Submit1" type="submit"
value="submit"
onclick="CopyTextToHiddenField()" />
<input name="Hidden1" type="hidden" />
</form>

Ass this JavaScript in the Head section
of page to be posted

<script language="javascript">
function CopyTextToHiddenField()
{
var textbox1Value = document.getElementById
("<%=TextBox1.ClientID%>").value;

document.forms[1].document.getElementById
("Hidden1").value = textbox1Value;
}
</script>

To retrieve the value of hidden field
in Default2.aspx page

lblData.Text = Request.Form["Hidden1"];

Server.Transfer Method in ASP.NET

Server.Transfer method sends (transfers) all the state information
all application/session variables and all items in the request collections)
created in one ASPX page to a second ASPX page.

you can't use Server.Transfer to send the user to an external site
The Server.Transfer method also has a second parameter—"preserveForm". If you set this to True, using a statement such as Server.Transfer("WebForm2.aspx", True), the existing query string and any form variables will still be available to the page you are transferring to.

For example, if your Default.aspx has a TextBox control called TextBox1 and you transferred to Default2.aspx with the preserveForm parameter set to True, you'd be able to retrieve the value of the original page TextBox control by referencing Request.Form("TextBox1").

protected void Button1_Click1
(object sender, EventArgs e)
{
Server.Transfer("Default2.aspx", true);
}

Now in Default2.aspx page_load event
use the below code to get the value of TextBox1

Response.Write(Request.Form["TextBox1"]);

No comments: