ASP.NET - 如何获取 ContentPlaceHolder 中的 Div 控件?
我出于测试目的创建了非常简单的网站。只有一个母版页和一个内容页。
我的内容页面如下所示:
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div id="TestDiv1">bla bla</div>
<div id="TestDiv2">ble ble</div>
</asp:Content>
现在,根据某些条件我想显示/隐藏给定的 div。所以我试图通过 Controls 集合到达这些 div 之一,如下所示:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ContentPlaceHolder myContent = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
myContent.FindControl("TestDiv1").Visible = false; //this is not working
}
}
}
}
但上面的示例不起作用。 myContent.Controls
集合中不存在这两个 div 控件。例如,如果我在内容页面上放置一个文本框,我可以通过控件访问它。
那么我应该怎么做才能访问div控件呢?
I've created very simple web site for the test purposes. Only one master page and one content page.
My content page looks like this:
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div id="TestDiv1">bla bla</div>
<div id="TestDiv2">ble ble</div>
</asp:Content>
Now, based on some condition I would like to show/hide a given div. So I am trying to reach one of those divs by Controls collection, like this:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ContentPlaceHolder myContent = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
myContent.FindControl("TestDiv1").Visible = false; //this is not working
}
}
}
}
But the above example is not working. None of the two div control exists in the myContent.Controls
collection. If I place for example a TextBox on my content page, I can reach it through Controls.
So what should I do to be able to access the div control?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的 div 是 HTMLcontrols,请尝试将它们添加到标签 runat="server"
这应该可以解决您的问题。
your divs are HTMLcontrols, try to add them the tag runat="server"
That should solve your issue.
您需要在 div 上设置
runat="server"
。You need to set
runat="server"
on the divs.