代码之家  ›  专栏  ›  技术社区  ›  Maverick

在asp.net页面的服务器端代码中使用eval

  •  1
  • Maverick  · 技术社区  · 14 年前
    <asp:Repeater ID="rptrParent" runat="server">
    <ItemTemplate>
            <li>
                <a href="<% =ResolveUrl("~/cPanel/UserView.aspx?User=")%><%# Eval("StudentUserName") %>">
                    <span>
                        <%  ProfileCommon pc = new ProfileCommon();
                            pc.GetProfile(Eval("StudentUserName").ToString());
                            Response.Write(pc.FirstName + "" + pc.LastName);
                        %>
                    </span>
                </a>
            </li>
    </ItemTemplate>
    

    以下错误

    Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.
    

    就在这部分

    <%  ProfileCommon pc = new ProfileCommon();
        pc.GetProfile(Eval("StudentUserName").ToString());
        Response.Write(pc.FirstName + "" + pc.LastName);
    %>
    
    2 回复  |  直到 14 年前
        1
  •  4
  •   Nick Craver    14 年前

    在这种情况下,您需要这样的完整调用:

    <%#  Databinder.Eval(Container.DataItem,"StudentUserName") %>
    
        2
  •  0
  •   Maverick    14 年前

    好了,伙计们,谢谢你们的帮助,但我找到了解决办法:

    <asp:Repeater ID="rptrParent" runat="server" onitemdatabound="rptrParent_ItemDataBound">
    <ItemTemplate>
            <li>
                <a href="<% =ResolveUrl("~/cPanel/UserView.aspx?User=")%><%# Eval("StudentUserName") %>">
                    <span>
                        <asp:Literal ID="lblUserName" runat="server"></asp:Literal>
                    </span>
                </a>
            </li>
    </ItemTemplate>
    

    在代码隐藏文件中,我编写了以下函数:

    protected void rptrParent_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item)
        {
            Literal UserName = e.Item.FindControl("lblUserName") as Literal;
            String uName = DataBinder.Eval(e.Item.DataItem, "StudentUserName").ToString();
            ProfileCommon pc = Profile.GetProfile(uName);
            UserName.Text = pc.FirstName + " " + pc.LastName + " [ " + uName + " ]";
        }
    }