asp.net - 在母版页内的无序列表中找到转发器?

标签 asp.net master-pages

我已将 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">

这意味着中继器位于与顶级元素不同的“命名容器”中,并且无法从母版页的代码隐藏文件中直接访问。

要解决此问题,您需要执行以下任一操作

  1. 删除 runat="server"从这些控件(如果您实际上不需要从服务器端代码访问它们)。这将使您的代码按照现在的方式工作。 或者
  2. 将 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/

相关文章:

asp.net - 将友好URL添加到多语言ASP.NET网站,而不使用MVC

c# - 确定特定命名空间的 NuGet 包

c# - ObjectDataSource 使用带有构造函数的服务类

asp.net - 如何创建基于Web的可视化流程设计器?

c# - 如何从内容页检索母版页中的控件

asp.net - 在来自母版页的一页中隐藏一个 div

asp.net - 在 IIS 中的 .aspx 页面中使用 Python

asp.net - 如何为设计人员提供 ASP .NET 母版页的轻松编辑?

C# .NET 网站 - 向菜单元素添加 CSS 类

c# - 如何将母版页的 ScriptManager 放入子页的代码隐藏在 c# (.cs) 文件中