3

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

我认为我可以实现的一种解决方案是使用 Literal 控件并<a href...在需要链接的行上使用 HTML ()。这将需要重新处理一些旧代码,所以在我尝试之前,我真的很想知道这是否可能与现有的 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”属性的项目转换为链接,而不是将所有项目转换为链接。

4

1 回答 1

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>

黑客的方式

将 URL 值设置为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 但它应该很接近

于 2012-10-26T03:27:53.777 回答