Programmatically adding a hyperlink to a bulleted list that IS NOT DisplayMode=Hyperlink

拥有回忆 提交于 2019-12-04 15:00:41

You may find it's easier to use an <asp:Repeater /> for that task.

Something like:

<asp:Repeater ID="Repeater1" runat="server">
    <HeaderTemplate><ul></HeaderTemplate>
    <ItemTemplate>
        <li><%# string.IsNullOrEmpty(Eval("url").ToString()) ? Eval("text") : string.Format("<a href=\"{0}\">{1}</a>", Eval("url").ToString(), Eval("text").ToString()) %></li>
    </ItemTemplate>
    <FooterTemplate></ul></FooterTemplate>
</asp:Repeater>

Hackalicious Way

set the URL value to DataValueField when data binding the BulletedList

use the DataBound event to iterate through the items and add an attribute to each one with a URL value

protected void BulletedList1_DataBound(object sender, EventArgs e)
{
    foreach (ListItem i in BulletedList1.Items)
    {
        if (i.Value.Length > 0)
        {
            i.Attributes.Add("data-url", i.Value);
        }
    }
}

use JavaScript/jQuery to apply the necessary markup:

$('[data-url]').each(function() {
    var $this = $(this);
    $this.html('<a href="' + $this.attr('data-url') + '">' + $this.text() + '</a>');
});

didn't test this jQuery but it should be close

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!