以编程方式将超链接添加到不是DisplayMode = Hyperlink的项目符号列表

时间:2012-10-26 02:53:42

标签: c# asp.net controls web-controls bulletedlist

我有一个ASP.NET项目符号列表控件,直到今天才创建并仅用于纯文本。一个新的设计请求要求我将这些项目中的一些转换为超链接。因此,项目符号列表最终将需要包含一些纯文本项和一些超链接。如果我将其更改为DisplayMode = Hyperlink,即使我将值保留为空白,应该只是纯文本的条目仍然会成为可点击的链接。

我认为我可以使用的一个解决方案是使用Literal控件并在需要链接的行上使用HTML(<a href...)。这将需要重新处理一些旧代码,所以在我尝试之前我真的想知道这是否可以与现有的BulletedList一起使用。


修改

我真的无法在任何地方找到任何关于此的内容,我通常认为自己是一个非常优秀的Google员工。因此,对于在下一个十年的某个时间发现自己处于同一情景中的一两个迷茫和迷茫的灵魂,这是我完整实施下面提供的优秀答案:

在页面的代码隐藏中:

foreach (SupportLog x in ordered)
{
    blschedule.Items.Add(new ListItem(x.Headline, "http://mysite/Support/editsupportlog.aspx?SupportLogID=" + x.SupportLogID));
}

blschedule.DataBind();

注意最后的DataBind ---这是落入DataBound事件所必需的:

protected void blschedule_DataBound(object sender, EventArgs e)
{
    foreach (ListItem x in blschedule.Items)
    {
        if (x.Value.Contains("http")) //an item that should be a link is gonna have http in it, so check for that
        {
            x.Attributes.Add("data-url", x.Value);
        }
    }
}

在.aspx页面的头部:

<script src="<%# ResolveClientUrl("~/jquery/jquery141.js") %>" type="text/javascript"></script>
    <script>

        $(document).ready(function () {

           $('#<%=blschedule.ClientID %> li').each(function () {
               var $this = $(this);
               var attr = $this.attr('data-url');

               if (typeof attr !== 'undefined' && attr !== false) {
                   $this.html('<a href="' + $this.attr('data-url') + '">' + $this.text() + '</a>');
               }
           });
       });

    </script>

需要if语句以确保仅将具有“data-url”属性的项目转换为链接,而不是将所有项目转换为链接。

1 个答案:

答案 0 :(得分:2)

您可能会发现使用<asp:Repeater />更容易完成该任务。

类似的东西:

<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

在绑定DataValueField

的数据时将网址值设置为BulletedList

使用DataBound事件迭代项目并使用URL值为每个项目添加属性

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

使用JavaScript / jQuery应用必要的标记:

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

没有测试这个jQuery但它应该关闭