Library code snippets
Cross page postbacks in ASP.NET 2.0
ASP.NET 2.0 introduces the ability to have an ASPX page postback to a different ASPX page with cross page postbacks. This was done all the time in ASP but wasn't supported in ASP.NET 1.x. This wasn't directly supported because on the server you need the same page to be recreated upon postback so the same controls could be repopulated with the post data. Since the model is to work at a higher level with server side controls and their properties, posting back to a different page would force you to access Request.Form to fetch the data a user had entered, which is a lower level than the control model wants.
So, in v2.0 they came up with a way to support cross page postbacks. This is enabled by a button on the first page setting PostBackUrl property to the page that will handle the postback. Once in the second page you can access the controls from the previous page by accessing the Page.PreviousPage property. Here's a sample that's like most of the documentation I've seen:
// Page1.aspx
<form id="form1" runat="server">
<asp:TextBox runat="server" ID="_tb1"></asp:TextBox>
+
<asp:TextBox runat="server" ID="_tb2"></asp:TextBox>
<asp:Button runat="server" ID="_button"
PostBackUrl="~/Page2.aspx" Text=" = " />
</form>
// Page2.aspx
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
TextBox tb1 = (TextBox)PreviousPage.FindControl("_tb1");
TextBox tb2 = (TextBox)PreviousPage.FindControl("_tb2");
int sum = Int32.Parse(tb1.Text) + Int32.Parse(tb2.Text);
_result.Text = sum.ToString();
}
</script>
<form id="form1" runat="server">
Answer is: <asp:Label runat="server" ID="_result"></asp:Label>
</form>
I find this to be entirely too tedious primarily because this approach still loses out of the declarative server side object model. The second page has to re-declare the same controls as local variables to access the properties. I don't think it will be how people write their second page to handle the postback. Instead the more useful approach will be to use the <%@ PreviousPageType %> directive in the second page:
// Page1.aspx
<script runat="server">
public int Sum
{
get
{
return Int32.Parse(_tb1.Text) + Int32.Parse(_tb2.Text);
}
}
</script>
<form id="form1" runat="server">
<asp:TextBox runat="server" ID="_tb1"></asp:TextBox>
+
<asp:TextBox runat="server" ID="_tb2"></asp:TextBox>
<asp:Button runat="server" ID="_button"
PostBackUrl="~/Page2.aspx" Text=" = " />
</form>
// Page2.aspx
<%@ PreviousPageType VirtualPath="~/Page1.aspx" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
_result.Text = PreviousPage.Sum.ToString();
}
</script>
<form id="form1" runat="server">
Answer is: <asp:Label runat="server" ID="_result"></asp:Label>
</form>
The first page utilizes the posted data via the declarative controls and it provides the necessary information to the second page a public property. Now this is much better since we now get to reuse the declarative controls. I really think this will be the preferred style of using cross page postbacks in ASP.NET 2.0.
One very interesting thing I've noticed about cross page postbacks is the life cycle of the first page when posting back to the second. The first time the second page accesses Page.PreviousPage ASP.NET needs to make a page object available. So it, in essence, creates the Page.PreviousPage object and calls ProcessChildRequest , which is similar to ProcessRequest except it stops processing prior to PreRender and a fake Response object is created so that no Write s are emitted. This has some interesting side effects, one of which is that all of the server side events of the first page fire. This includes Page_Init , Page_Loadand any control events like Button.Click events (if the Button has an OnClick event declared). This blew me away and it's certainly something to keep in mind when using cross page postbacks. One way to detect if your page is being accessed as a PreviousPage is to check Page.IsCrossPagePostBack .
One last thing to note about cross page postbacks is that using tracing is a PITA, since the PreviousPage's Trace messages end up mixed with the current page's Trace messages. I submitted a request to the product feeback center to see what they could do about it.
This was originally published on Brock Allen's Blog here
Related articles
Related discussion
-
Gizmox Announces release of Visual WebGui SDK version 6.2.2
by Visual WebGui (0 replies)
-
Error 4 Make sure that the class defined in this code file matches the 'inherits' attribute, and that it extends the correct base class (e.g. Page or UserControl).
by lbargers (3 replies)
-
How to receive data in web server sending from GPRS modem
by AshokSingh (1 replies)
-
Working with frames in c# .net
by pulak2008 (0 replies)
-
Time Out Problem
by lorrainepetty (1 replies)
Related podcasts
-
CodeCast Episode 4: State of .NET, IE8, ASP.NET MVC, and O'Reilly Media
CodeCast Episode 4: State of .NET, IE8, ASP.NET MVC, and O'Reilly MediaHosts Ken Levy and Markus Egger discuss the new State of .NET events, IE8, ASP.NET MVC, followed by an interview from PDC with two editors from O'Reilly Media. More on ASP.NET MVC can be found at http://asp.net/mvc. Interview...
Related jobs
-
Microsoft .Net Architect
in AMSTERDAM (€50K-€90K per annum) -
Microsoft Dynamics CRM Technical Consultant
in Netherlands (€50K-€90K per annum) -
.net developer
in Rijswijk (€2K-€4K per annum)
Events coming up
-
Dec
9
Internet Information Services 7.0 for ASP.Net Developers
Glasgow, United Kingdom
One of the biggest and best new features of Windows Server 2008 and Windows Vista is Internet Information Server 7.0. IIS 7.0 is the latest and most significant release of Microsoft's Web Server. With this release comes a new extensibility model which gives developers more options than ever before, more diagnostic tools with which developers can debug and locate issues. During the session Andrew will investigate the new architecture, look at extending, configuring and developing for IIS7, ta...
adsadasd
dsfsdfdsfdsf
Whenever a page gets loaded i don't want a image control appears beside the textbox . but when the textbox got focus the image control apper beside it . How to do it as gotfocus() event is not wirking for textbox. Can u give me any sample code.Please help me it's very urgent...
hsadsadlaskdsad
You're totally wrong.
Let's assume you want to access a HiddenField value on the calling page, and the calling page is, as you said, a content page of a masterpage. You "simply" do it this way:
string a = ((HiddenField)PreviousPage.Master.FindControl("Form1").FindControl("ContentPlaceHolder1").FindControl("HiddenField1")).Value
You get empty controls cause you are doing ((HiddenField)PreviousPage.FindControl("HiddenField1")).Value... That obviously can't work, cause you have to begin at the root (PreviousPage.Master) and then follow the control annidation.
Regards,
Sgro
When you have a master page for the source, the target page can't grab the source. It only gets the source page such as its name but not its controls on the source page. If you put the <% @PreviousPageType VirtualPath="~/yoursourcefile.aspx" %>, that resolve the issue. But, that limits on the number of incoming page for target page to one!
dont start banging ur head if u r getting any error while creating pdf file crystal report.. go thru these steps..
1) in ur visual studio .net right click on solution expl of ur project and add an .xsd file. this is for creating a new schema that u need for the report,,
2)in ur schema file that is ur xsd file select what ever database files u want from the server explorer that u find on the right side. this will create a new shema which u can use as a source in ur report..
3) add a report in to ur porject and then in the database expert .. select more data source..then select ado.net(xml) ,, .. now xml file path will be asked select the xsd file that u just created,, now add the newdataset which just got created to the right list box by clicking on the > button
4) now from the field explr select the fileds into the report
5) now time for some coding,,
if u r writing the code in some button click include this
private void Button1Click(object sender, System.EventArgs e)
{
string tableName = "TESTHARISH"; string rptFile = "PDFTest.rpt";
string xsdFile = "PDFTest.xsd";
string pdfFile = "MailPDF.pdf";
DataTable dattblPDF = new DataTable();
dattblPDF = GetTable();
dattblPDF.TableName = tableName;
DataSet datsetPDF = new DataSet();
datsetPDF.Tables.Add(dattblPDF.Copy());
CreateShemaFile(xsdFile, datsetPDF);
// Report document
ReportDocument rptdocPDF = new ReportDocument();
string strFileNameRPT = Server.MapPath(rptFile);
rptdocPDF.Load(strFileNameRPT);
rptdocPDF.ReportOptions.EnableSaveDataWithReport = false;
rptdocPDF.SetDataSource(datsetPDF);
ExportOptions expoptPDF = rptdocPDF.ExportOptions;
expoptPDF.ExportFormatType = ExportFormatType.PortableDocFormat;
expoptPDF.ExportDestinationType = ExportDestinationType.DiskFile;
exp_optPDF.DestinationOptions = new DiskFileDestinationOptions();
DiskFileDestinationOptions diskOpts = new DiskFileDestinationOptions();
((DiskFileDestinationOptions)
// u can give the full path or u can use map path to find the full path
rptdocPDF.ExportOptions.DestinationOptions).DiskFileName = @"D:\PDFFile\MailPDF.pdf";
rptdocPDF.Export();
mail();
Response.Write("<a href=\"" + @"D:\PDFFile\MailPDF.pdf" + "\">" + pdfFile + "</a>");
}
/now include these function assuming that u r taking the data form a db and then putting it into a xsd and then tranfer to a report then convert it into a pdf format... please change the database name and stuffs like that according to ur project/
private DataTable GetTable()
{
DataTable dattblPDF = new DataTable("TESTHARISH");
SqlConnection con = new SqlConnection("Coonection string over here");
SqlDataAdapter sqldatadpPDF = new SqlDataAdapter("SELECT MANNO, PARTNO, NAME FROM TESTHARISHWITH (NOLOCK)" ,con  
DataSet datset = new DataSet();
sqldatadpPDF.Fill(datset, "TESTHARISH");
return datset.Tables["TESTHARISH"];
}
private void CreateShemaFile(string strFileNameXSD, DataSet datsetPDF)
{
string strServerFilePath = Server.MapPath(strFileNameXSD);
FileStream myFileStream = new FileStream (strServerFilePath, FileMode.Create);
XmlTextWriter myXmlWriter = new XmlTextWriter(myFileStream, Encoding.Unicode);
datsetPDF.WriteXml( myXmlWriter, XmlWriteMode.WriteSchema );
myXmlWriter.Close();
}
if u have anymore doubts please be free to mail me ,,, harishjan@india.com
The current implementation of the cross-page postback mechanism is far from ideal. First I was very happy when I noticed this new feature was in ASP.NET 2.0. But now, after some testing I see serious problems using this in my application.
One serious problem is that when the PreviousPage is build, it uses the QueryString of the CURRENT page. This is a serious issue. (in my application it is). I've posted a Bug report. What I just found out is that (in the beta 2) the Form variables from the posted cross-page can be fetched by the Page.Request.Form AND the Page.PreviousPage.Request.Form. This seems incorrect. Only Page.Previous.Request.Form should contain these values.
I am doing my project in ASP.Net . Whenever a page gets loaded i don't want a image control appears beside the textbox . but when the textbox got focus the image control apper beside it . How to do it as gotfocus() event is not wirking for textbox. Can u give me any sample code.Please help me it's very urgent...
Thanks & regards
Dipti
This thread is for discussions of Cross page postbacks in ASP.NET 2.0.