Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Page.PreviousPage always null?

I am experimenting with cross-page posting by following this MSDN article. I have this code:

CrossPagePosting1.aspx

<form id="form1" runat="server">
    <h1>Page 1</h1>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
    <asp:Button ID="Button1" runat="server" Text="Button" PostBackUrl="CrossPagePosting2.aspx"/>
</form>

CrossPagePosting2.aspx

<form id="form1" runat="server">
    <h1>Page 2</h1>
    <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</form>

CrossPagePosting2.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    TextBox TextBox1 = (TextBox)Page.PreviousPage.FindControl("TextBox1");
    Label1.Text = TextBox1.Text;
}

This code above produces a NullReferenceException at Page.PreviousPage. Why?

This is an ASP.Net 4.0 application.

It uses FriendlyUrls, which is the default.

NOTE: I do NOT want the previous page to be strongly-typed, e.g. using the PreviousPageType directive. According to the referenced article, this shouldn't be necessary.

like image 324
brainbolt Avatar asked Jan 24 '14 02:01

brainbolt


2 Answers

I found that Friendly URLS might get you this problem. By default, the Web Forms template includes ASP.NET Friendly URLs.

When you use the default WebForm from visual Studio, the AutoRedirectMode is set to Permanent. This makes you request into a "GET" and since you are using Friendly URLS, you can’t evaluate the PreviousPage.

Workarounds:

  • If you want a "POST" action then set the AutoRedirectMode = RedirectMode.Off (this will give you PreviousPage info but only from non-Friendly-Url pages [ex: www.you.com/mypage.aspx], however this will get you an error if you try to access the Friendly-Url page [ex: www.you.com/mypage] << no .aspx).

  • If you want the PreviousPage information you will have to set the previous post directive in you webpage <%@ PreviousPageType VirtualPath="~/Page1.aspx" %> OR maybe use the Server.Transfer in a OnClick Method.

like image 156
Breno Avatar answered Oct 29 '22 23:10

Breno


The problem here was being caused by FriendlyUrls, which were installed by default on the test site I was working in. I disabled FriendlyUrls, and it worked.

like image 41
brainbolt Avatar answered Oct 29 '22 21:10

brainbolt