如何在带有母版页的页面中使用PostbackUrl

th1*_*ey3 2 asp.net

任何人都可以给我一个PostbackUrl的工作示例,其中目标页面和上一页都有母版页.

例如,假设我有两个页面default1.axpxdefault2.aspx.它们都有一个母版页MyMasterpage.masterpage

我想从default1.aspx回发到default2.aspx,然后从default2页面的default1页面控件中提取数据.

我怎样才能做到这一点?

Eri*_*sch 7

你应该把这个问题命名为"如何找到一个控件ContentPlaceholder?",因为你的问题PreviousPage不是不起作用,而是你不明白它是如何ContentPlaceholder工作的.

这个问题与母版页本身无关,而且与使用a是完全相关的ContentPlaceholder,这是asp.net用语中的命名容器. FindControls不会在命名容器内搜索,这正是它们的设计方式.

PreviousPage与母版页一起工作正常,因此我对他们与你的问题有什么关系感到困惑.您可以访问上一页中您想要的任何属性,它实际上可以工作.例如:

 HtmlForm form = PreviousPage.Form; // this works fine
 Control ctrl = PreviousPage.Master.FindControl("TextBox1"); // this works as well
Run Code Online (Sandbox Code Playgroud)

你可能遇到的问题是你试图用来FindControl()在内容页面中找到一个特定的控件,而且它不能正常工作,正是因为你在PreviousPage上调用了FindControl,而不是在控制你的命名容器上正在寻找存在.

要找到所需的控件,只需FindControl在命名容器上执行操作即可.假设占位符名为ContentPlaceHolder1,以下代码可以正常工作.

var ph = PreviousPage.Controls[0].FindControl("ContentPlaceHolder1");
var ctl = ph.FindControl("TextBox1");
Run Code Online (Sandbox Code Playgroud)

您可以PreviousPage使用以下代码验证此问题与此无关,该代码仅使用单个页面并查找自身的控件.在Default.aspx页面上放置一个名为TextBox1的文本框.然后,在Page_LoadDefault.aspx.cs后面的代码函数中放入此代码,然后在调试器中运行它并逐步执行它.

protected void Page_Load(object sender, EventArgs e)
{
    // Following code should find the control, right?  Wrong. It's null
    var ctrl = Page.FindControl("TextBox1"); 

    // assuming your content placeholder in the masterpage is called MainContent, this works.
    var ctrl = Page.Controls[0].FindControl("MainContent").FindControl("TextBox1");
}
Run Code Online (Sandbox Code Playgroud)

所以,请不要说" PreviousPage如果页面有母版页就不能正常工作",因为它的工作正常.问题是你不知道它应该如何工作.了解页面对象模型的工作原理.