0

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

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

塞纳里奥:

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

案例一:【无母版页发帖】

数据正常发布。

案例 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”。

案例一:【无母版页发帖】

colec.Count 返回5

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

colec.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 ?

4

1 回答 1

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" />

但是,当您不使用母版页时,没有“ContentPlaceHolder”,因此 TextBox1 将呈现如下:

<input name="TextBox1" type="text" id="TextBox1" />
于 2014-12-25T19:24:13.647 回答