15

是否可以从为母版加载的页面访问母版页上的元素ContentPlaceHolder

我有一个 ListView,它在母版页的导航区域中列出了人们的姓名。我想在将一个人添加到 ListView 数据绑定到的表中后更新 ListView。在ListView重新加载缓存之前,当前不会更新它的值。我们发现只要重新运行ListView.DataBind()就会更新列表视图的内容。我们无法在ListView.DataBind()使用母版页的页面上运行。

下面是我想做的一个示例,但是编译器错误说

“当前上下文中不存在 PeopleListView”

GIS.master - ListView 所在的位置

...<asp:ListView ID="PeopleListView"...

GISInput_People.aspx - 使用 GIS.master 作为它的母版页

GISInput_People.aspx.cs

AddNewPerson()
{
    // Add person to table
    ....

    // Update Person List
    PeopleListView.DataBind();
    ...
}

在 C# .Net 中解决此类问题的最佳方法是什么?

4

6 回答 6

17

我相信你可以通过使用 this.Master.FindControl 或类似的东西来做到这一点,但你可能不应该 - 它需要内容页面对母版页的结构了解太多。

我会建议另一种方法,例如在内容区域中触发一个事件,主人可以在触发时侦听并重新绑定。

于 2008-08-08T21:46:22.053 回答
3

假设该控件在母版页上称为“PeopleListView”

ListView peopleListView = (ListView)this.Master.FindControl("PeopleListView");
peopleListView.DataSource = [whatever];
peopleListView.DataBind();

但是@palmsey更正确,特别是如果您的页面可能有多个母版页。将它们解耦并使用事件。

于 2008-08-08T21:48:28.193 回答
2

选项 1:您可以创建母版页控件的公共属性

public TextBox PropMasterTextBox1
{
    get { return txtMasterBox1; }
    set { txtMasterBox1 = value; }
}

在内容页面上访问它,例如

Master.PropMasterTextBox1.Text="SomeString";

选项 2:在母版页上:

public string SetMasterTextBox1Text
{  
    get { return txtMasterBox1.Text; }
    set { txtMasterBox1.Text = value; }
}

在内容页面上:

Master.SetMasterTextBox1Text="someText";

选项 3:您可以创建一些适合您的公共方法


这些方法不是那么有用,但如果您只想使用一些有限和预定义的控件,它会有所帮助

于 2012-06-08T08:43:20.650 回答
1

要记住的一个想法是以下 ASP.NET 指令。

<%@ MasterType attribute="value" [attribute="value"...] %>

MSDN 参考

在引用 this.Master 时,它将通过创建对母版页的强类型引用来帮助您。然后,您可以引用您的 ListView 而无需 CAST。

于 2008-08-23T02:33:55.063 回答
0

您可以使用代码 this.Master.FindControl(ControlID) 访问您想要的控件。它返回控件的引用,使更改生效。不可能在每种情况下都触发一个事件。

于 2011-04-08T07:08:36.080 回答
-1

假设您的母版页名为 MyMaster:

(Master as MyMaster).PeopleListView.DataBind();

编辑:由于 PeopleListView 将被默认声明为受保护,您需要将其更改为公共,或创建一个公共属性包装器,以便您可以从您的页面访问它。

于 2008-08-08T21:44:53.863 回答