Dynamically generated bulleted list from code behi

2019-08-05 14:02发布

问题:

Please, could you help me and tell me how can I generated dynamically this piece of code:

<li>
          <a href="../adGallery/images/pictures/1.jpg">
            <img src="../adGallery/images/pictures/thumbs/1.jpg" class="image0"/>
          </a>
        </li>
        <li>
          <a href="../adGallery/images/pictures/2.jpg">
            <img src="../adGallery/images/pictures/thumbs/2.jpg" title="A title for 10.jpg" alt="This is a nice, and incredibly descriptive, description of the image 10.jpg" class="image1"/>
          </a>
        </li>

from my code behind?

Thank you very much

回答1:

I would suggest to use a Repeater which enables to customize your controls as much as possible. A BulletedList control is limited. Here's an attempt anyway:

<asp:BulletedList id="ImagesBulletedList" 
        BulletStyle="Disc"
        DisplayMode="HyperLink" 
        OnClick="ImageBulletedList_Click"
        runat="server">    
</asp:BulletedList>

codebehind:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        ListItem listItem = new ListItem("Picture 1", "../adGallery/images/pictures/1.jpg");
        listItem.Attributes.Add("class", "image0");
        ImagesBulletedList.Items.Add(listItem);
        listItem = new ListItem("Picture 2", "../adGallery/images/pictures/2.jpg");
        listItem.Attributes.Add("class", "image1");
        listItem.Attributes.Add("title", "A title for 10.jpg");
        ImagesBulletedList.Items.Add(listItem);
        // ...
    }
}


回答2:

Use an asp:Repeater control.

Here is a tutorial on doing exactly this kind of thing:

http://www.codeguru.com/csharp/.net/net_asp/controls/article.php/c19299/The-ASPNET-Repeater-Web-Server-Control.htm



回答3:

Use this code method:

private string getDynamicHTML(int count)
{
    string message = "<ul>";
    for (int i = 0; i < count; i++)
    {
        message = message + "<li>";
        message = message + "<a href='../adGallery/images/pictures/" + i +".jpg'>";
        message = message + "<img src='../adGallery/images/pictures/thumbs/" + i + ".jpg' title='A title for 10.jpg' alt='This is a nice, and incredibly descriptive, description of the image 10.jpg' class='image1'/></a>";
        message = message + "</li>";
    }
    return message + "</ul>";
}

and place a label in the required position and bind the result to that label

Label1.Text=getDynamicHTML(10);

This will render as required HTML