2014-01-24 64 views
4

我正在通过以下this MSDN article试验跨页面发布。我有这样的代码:为什么Page.PreviousPage始终为空?

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; 
} 

上面的代码产生NullReferenceExceptionPage.PreviousPage。为什么?

这是一个ASP.Net 4.0应用程序。

它使用了FriendlyUrls,这是默认值。

注意:我不希望前一页是强类型的,例如,使用PreviousPageType指令。根据引用的文章,这不应该是必要的。

回答

1

这里正被FriendlyUrls引起的问题,这是默认安装在测试现场,我在工作。我禁用FriendlyUrls ,它的工作。

0

我认为下面的文章会帮助你。

http://csharpdotnetfreak.blogspot.com/2009/08/cross-page-posting-in-aspnet.html

有两种方法如何使用跨页投递回传

+0

我读张贴我的问题之前那篇文章。据我所知,它不能解决我的问题。你看到我的代码有什么特定的问题吗? – brainbolt

+0

你的代码很好。我认为你只能通过在你的page.Page中添加PreviousPageType指令来做到这一点。http://www.cosnetics.co.uk/articles/cross-page-posting-not-working/ – Chirag

+0

Strongly-在这种情况下,输入上一页不是一个选项。 – brainbolt

-1

发生这种情况的原因很简单,因为您没有正确设置postbackurl属性。

如果CrossPagePosting2.aspx是在你的程序改变一项PostBackUrl的根~/CrossPagePosting1.aspx

你并不需要添加<%@ PreviousPageType%>使用PostBackUrl属性时指令。使用PreviousPage.FindControl(id)将搜索使用postbackurl属性发布的表单元素

+0

上一页报告为null的原始问题与此情况下的回发网址无关,但与使用路线(与友好的网址) – Marcel

4

我发现Friendly URLS可能会给你带来这个问题。默认情况下,Web窗体模板包含ASP.NET友好URL。

当您使用Visual Studio的默认WebForm时,AutoRedirectMode被设置为Permanent。这使您请求进入“GET”,并且由于您使用的是友好URL,因此无法评估PreviousPage。

解决方法:

  • 如果你想要一个“POST”的行动,那么设置AutoRedirectMode = RedirectMode.Off(这会给你|上一页信息,但仅从 非友好的URL的网页[例如:www.you.com/mypage.aspx],但如果您尝试访问Friendly-Url页面[例如: www.you。此 会给您一个错误。com/mypage] < < no .aspx)。

  • 如果你想那么PreviousPage信息,你将不得不在你的网页<%@ PreviousPageType VirtualPath设置 以前的帖子指令=“〜/ Page1.aspx的”%>或可能使用的Server.Transfer在 OnClick方法。

0

试试这个

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