ESD
ESD

Reputation: 545

automatically generating a list of links

Ok so I am trying to make a list of links in a page that is generated using a foreach and loop as long as there are objects in the list. Here is the code that I use to generate the links:

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++;
                }
            }
        }
    }

For some reason, the links are unclickable. I get this:

screenshot of the links

How can I make links that do not lead to another page but instead launch a method in the C# code of the page?

Upvotes: 2

Views: 4130

Answers (1)

Leniel Maccaferri
Leniel Maccaferri

Reputation: 102398

You can create LinkButton controls that call subroutines/methods in your ASPX code:

Sample code:

<%@ 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>

In your specific case, add a ContentPlaceHolder in your master page:

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

In the page where you want the links to appear you add a Content control like so:

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

</asp:Content>

Then foreach link you want, do this:

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);
}

Upvotes: 2

Related Questions