2

我已将我的 html 模板加载到我的母版页中,然后将类别绑定到数据库。我用过这个编码。

<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 页面上进行编码将此转发器绑定到我的数据库。

 if (!IsPostBack)
        {
            DataSet ds = new ViewAction().GetAllProductCategoryData();
            repCategories.DataSource = ds;
            repCategories.DataBind();
        }

但它显示的错误是

"The name repCategories does not exist in the current context"

为什么它显示这个错误帮助我解决这个问题。请

4

1 回答 1

2

您的代码(如编写的)不起作用的原因是,Repeater 嵌套在其他 2 个服务器控件中:

  • <li runat="server">
  • <ul class="categories" runat="server" id="categorylist">.

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

要解决此问题,您需要

  1. 从这些控件中删除runat="server"(如果您实际上不需要从服务器端代码访问它们)。这将允许您的代码以现在的方式工作。 或者,
  2. <li>元素添加一个 ID,然后使用该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();
}

您需要使用该代码在任何需要在代码隐藏中访问它的地方“获取”中继器。

于 2013-08-07T13:02:31.643 回答