Monday, January 14, 2008

Performing Cross-Page Posts (1)

By default, if you click a button control, the page containing the control is posted back to itself and the same page is reloaded. However, you can use the PostBackUrl property to post form data to another page.

ButtonSearch.aspx

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head id="Head1" runat="server">

<title>Button Search</title>

</head>

<body>

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

<div>

<asp:Label

id="lblSearch"

Text="Search:"

Runat="server" />

<asp:TextBox

id="txtSearch"

Runat="server" />

<asp:Button

id="btnSearch"

Text="Go!"

PostBackUrl="ButtonSearchResults.aspx"

Runat="server" />

</div>

</form>

</body>

</html>


ButtonSearchResults.aspx


<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

Sub Page_Load()

If Not IsNothing(PreviousPage) Then

Dim txtSearch As TextBox = CType(PreviousPage.FindControl("txtSearch"), TextBox)

lblSearch.Text = String.Format("Search For: {0}", txtSearch.Text)

End If

End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head id="Head1" runat="server">

<title>Button Search Results</title>

</head>

<body>

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

<div>

<asp:Label

id="lblSearch"

Runat="server" />

</div>

</form>

</body>

</html>


In the Page_Load event handler in ButtonSearchResults.aspx, the PreviousPage property is used to get a reference to the previous page. Next, the FindControl() method is used to retrieve the txtSearch TextBox control from the previous page. Finally, the value entered into the TextBox is displayed in a label on the page.

ASP.NET 2.0 Unleashed

blog comments powered by Disqus