是否可以从ContentPlaceHolder中为母版加载的页面访问母版页面上的元素?
我有一个ListView,它在"母版"页面的导航区域中列出了人的名字。在将一个人添加到ListView数据绑定到的表中之后,我想更新ListView。 ListView当前在重新加载缓存之前不会更新其值。我们发现仅重新运行ListView.DataBind()将会更新列表视图的内容。我们无法在使用"母版"页面的页面上运行ListView.DataBind()。
下面是我想做的一个示例,但编译器错误显示
"PeopleListView does not exist in the current context"
GIS.master-ListView所在的位置
1
| ...<asp:ListView ID="PeopleListView"... |
GISInput_People.aspx-使用GIS.master作为其主页
GISInput_People.aspx.cs
1 2 3 4 5 6 7 8 9
| AddNewPerson()
{
// Add person to table
....
// Update Person List
PeopleListView.DataBind();
...
} |
在C#.Net中解决此类问题的最佳方法是什么?
我相信您可以使用this.Master.FindControl或类似的方法来做到这一点,但是您可能不应该-它要求内容页面对母版页的结构了解太多。
我建议使用另一种方法,例如在内容区域中触发一个事件,使主机可以监听并在触发时重新绑定。
假定该控件在母版页上称为" PeopleListView"
1 2 3
| ListView peopleListView = (ListView)this.Master.FindControl("PeopleListView");
peopleListView.DataSource = [whatever];
peopleListView.DataBind(); |
但是@palmsey更正确,特别是如果您的页面可能有多个母版页的情况。解耦它们并使用一个事件。
选项1:您可以创建母版页控件的公共属性
1 2 3 4 5
| public TextBox PropMasterTextBox1
{
get { return txtMasterBox1; }
set { txtMasterBox1 = value; }
} |
在内容页面上访问它,例如
1
| Master.PropMasterTextBox1.Text="SomeString"; |
选项2:
在母版页上:
1 2 3 4 5
| public string SetMasterTextBox1Text
{
get { return txtMasterBox1.Text; }
set { txtMasterBox1.Text = value; }
} |
内容页面上的
:
1
| Master.SetMasterTextBox1Text="someText"; |
选项3:
您可以创建一些适合您的公共方法
这些方法不是那么有用,但是如果您只想使用一些有限的和预定义的控件,它会有所帮助
要记住的是以下ASP.NET指令。
1
| <%@ MasterType attribute="value" [attribute="value"...] %> |
MSDN参考
通过创建对母版页的强类型引用,在引用this.Master时将为您提供帮助。然后,您可以引用ListView而不需要进行CAST。
您可以使用代码this.Master.FindControl(ControlID)来访问所需的控件。它返回控件的引用,以便更改生效。在每种情况下都不可能触发事件。
假设您的母版页名为MyMaster:
1
| (Master as MyMaster).PeopleListView.DataBind(); |
编辑:由于默认情况下PeopleListView将被声明为受保护的,因此您需要将其更改为public,或者创建一个公共属性package器,以便可以从页面访问它。