无法使用母版页将数据从一个内容页面传递到另一个内容页面

时间:2014-12-25 18:45:48

标签: asp.net master-pages nullreferenceexception content-pages

我正在尝试创建一个将数据发布到另一个网络表单的asp webform。

我做了两个单独的项目,一个使用母版页,一个不使用。

塞纳里奥:

WebForm1.aspx 有两个文本框和一个提交按钮

<table>
        <tr>
            <td >Name:</td>
            <td >
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            </td>
            <td class="auto-style1"></td>
        </tr>
        <tr>
            <td>Id:</td>
            <td>
                <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
            </td>
            <td>&nbsp;</td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td>
                <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
            </td>
            <td>&nbsp;</td>
        </tr>
    </table>

WebForm2.aspx.cs 有两个标签,应显示从WebForm1.aspx收到的数据

Page prevPage = this.PreviousPage;
        if (prevPage != null)
        {
            Label1.Text = ((TextBox)prevPage.FindControl("TextBox1")).Text;
            Label2.Text = ((TextBox)prevPage.FindControl("TextBox2")).Text;
        }

案例1:[没有母版页发布]

数据发布通常

案例2:[使用母版页发布]

我得到 NullReferenceException

所以我打破了代码。

Page prevPage = this.PreviousPage;
        if (prevPage != null)
        {
            ControlCollection collec = prevPage.Controls;
            Control ctrl= prevPage.FindControl("TextBox1");
            TextBox txtbx = (TextBox)ctrl;
            Label1.Text = txtbx.Text; //Exception raised here

            Label2.Text = ((TextBox)prevPage.FindControl("TextBox2")).Text;
        }

调试时: 我在立即窗口中执行了“collec.Count”。

案例1:[没有母版页发布]

collec.Count返回 5

案例2:[使用母版页发布]

collec.Count返回 1 [为什么? ]

后来,

我尝试使用公共属性传递数据

WebForm1.aspx.cs中

protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        Server.Transfer("WebForm2.aspx");
    }

    public string Name { get { return TextBox1.Text; } }
    public string ID { get { return TextBox2.Text; } }

WebForm2.aspx.cs

WebForm1 prevPage = (WebForm1)this.PreviousPage;
        if (prevPage != null)
        {
            ControlCollection c = prevPage.Controls;
            Label1.Text = prevPage.Name;
            Label2.Text = prevPage.ID;
        }

现在它可以正常工作,即使是母版页。

所以有人可以解释我发生了什么,以及为什么从一个内容页面发布到另一个内容页面,主人给我NullReferenceException?

1 个答案:

答案 0 :(得分:0)

首先,您必须查看提交页面的内容占位符

因此,代码看起来更像是这样:

ContentPlaceHolder placeHolder = (ContentPlaceHolder)PreviousPage.Master.FindControl("ContentPlaceHolder1");
        TextBox txt1 = (TextBox)placeHolder.FindControl("TextBox1");

当您使用母版页时,与ContentPlaceHolder1关联的Content控件中具有ID TextBox1的TextBox将使其id属性扩展如下:

<input name="ctl00$ContentPlaceHolder1$TextBox1" type="text" id="ContentPlaceHolder1_TextBox1" />

但是当你没有使用母版页时,没有&#39; ContentPlaceHolder&#39;所以TextBox1将呈现如下:

<input name="TextBox1" type="text" id="TextBox1" />