Why is the Page.PreviousPage always set to zero?

I am experimenting with cross-publishing 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 gives NullReferenceExceptionat 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, for example. using the directive PreviousPageType. According to this article, this is not necessary.

+4
source share
5 answers

FriendlyUrls, , . FriendlyUrls, .

+1

, Friendly URLS . Web Forms URL- ASP.NET.

WebForm Visual Studio, AutoRedirectMode "". "GET", Friendly URLS, .

:

  • "POST", AutoRedirectMode = RedirectMode.Off( PreviousPage, , URL- [ex: www.you.com/mypage.aspx], , Friendly-Url [ex: www.you.com/mypage] < .aspx).

  • , PreviousPage post - <% @PreviousPageType VirtualPath = "~/Page1.aspx" % > , , Server.Transfer OnClick.

+4

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack && PreviousPage != null)
        {
            Page page = PreviousPage;
            Label1.Text = ((TextBox)page.FindControl("TextBox1")).Text;
        }
    }
0

The reason this happens is simply because you set the postbackurl property incorrectly.

If CrossPagePosting2.aspx is at the root of your program, change postbackurl to ~/CrossPagePosting1.aspx

When using the postbackurl property, you do not need to add the <% @ PreviousPageType%> directive. using the PreviousPage.FindControl (id) method will search for form elements that are submitted using the postbackurl property

-1
source

Source: https://habr.com/ru/post/1523451/


All Articles