自动生成链接列表

时间:2012-10-22 00:53:44

标签: asp.net dynamic methods hyperlink

好的,所以我试图在使用foreach和循环生成的页面中创建链接列表,只要列表中有对象。这是我用来生成链接的代码:

protected void Page_Init(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["mamlist"] != null)
            {
                mamlist = (List<mammifere>)Session["mamlist"];

                int i = 0;
                foreach (mammifere l in mamlist)
                {
                    mamol.InnerHtml += ("<li><a onClick='select("+i+");' >" + l.Nom + "</a></li>");
                    i++;
                }
            }
        }
    }

由于某种原因,链接无法点击。我明白了:

screenshot of the links

如何制作不会导致其他网页的链接,而是在页面的C#代码中启动方法?

1 个答案:

答案 0 :(得分:2)

您可以创建调用ASPX代码中子例程/方法的LinkButton控件:

示例代码:

<%@ Page Language="C#" AutoEventWireup="True" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>LinkButton Example</title>
<script language="C#" runat="server">

      void LinkButton_Click(Object sender, EventArgs e) 
      {
         Label1.Text="You clicked the link button";
      }

   </script>

</head>
<body>

   <form id="form1" runat="server">

      <h3>LinkButton Example</h3>

      <asp:LinkButton id="LinkButton1" 
           Text="Click Me" 
           Font-Names="Verdana" 
           Font-Size="14pt" 
           OnClick="LinkButton_Click" 
           runat="server"/>

      <br />

      <asp:Label id="Label1" runat="server" />

   </form>

</body>
</html>

在您的具体情况下,在您的母版页中添加ContentPlaceHolder

<asp:contentplaceholder id="ContentPlaceHolder1" runat="server" />

在您希望显示链接的页面中,添加Content控件,如下所示:

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

</asp:Content>

然后是您想要的foreach链接,请执行以下操作:

foreach (mammifere l in mamlist)
{
    LinkButton linkButton = new LinkButton();

    linkButton.Text = l.Nom;

    linkButton.OnClick= "LinkButton_Click";

    linkButton.ID = l.Nom;     

    Content1.Controls.Add(linkButton);
}