我已将 html 模板加载到我的母版页中,然后将类别绑定(bind)到数据库。 我已经使用了这个编码。
<ul class="categories">
<li id="categoryItem">
<h4>Categories</h4>
<ul class="categories" id="categorylist">
<asp:Repeater ID="repCategories" runat="server">
<HeaderTemplate><ul></HeaderTemplate>
<ItemTemplate>
<li>
<asp:HyperLink ID="hyperCategories" runat="server"><%#Eval("CategoryName")%></asp:HyperLink>
</li>
</ItemTemplate>
<FooterTemplate></ul></FooterTemplate>
</asp:Repeater>
</ul>
</li>
并尝试通过在 master.cs 页面上进行编码来将此转发器绑定(bind)到我的数据库。
if (!IsPostBack)
{
DataSet ds = new ViewAction().GetAllProductCategoryData();
repCategories.DataSource = ds;
repCategories.DataBind();
}
但它显示错误
“名称repCategories在当前上下文中不存在”
为什么显示此错误帮助我解决这个问题。请
最佳答案
您的代码(所写的)无法正常工作的原因是因为该 Repeater 嵌套在另外 2 个服务器控件中:
-
<li runat="server">
和 -
<ul class="categories" runat="server" id="categorylist">
。
这意味着中继器位于与顶级元素不同的“命名容器”中,并且无法从母版页的代码隐藏文件中直接访问。
要解决此问题,您需要执行以下任一操作
- 删除
runat="server"
从这些控件(如果您实际上不需要从服务器端代码访问它们)。这将使您的代码按照现在的方式工作。 或者 - 将 ID 添加到
<li>
元素,然后使用FindControl
方法来访问嵌套的中继器。
选项二看起来像这样(我们假设您为 <li>
提供了“categoryItem”的 ID):
if (!IsPostBack)
{
// Get the Repeater from nested controls first
Repeater repCategories = (Repeater)categoryItem.FindControl("categorylist").FindControl("repCategories");
// Do the rest of your work
DataSet ds = new ViewAction().GetAllProductCategoryData();
repCategories.DataSource = ds;
repCategories.DataBind();
}
您需要使用该代码在任何需要在代码隐藏中访问它的地方“获取”转发器。
关于asp.net - 在母版页内的无序列表中找到转发器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18103739/