简体   繁体   English

如何在asp.net标签文本中嵌入html标签?

[英]How to embed an html tag within asp.net label text?

I am trying to create hyper link on condition of specific value of database field, it is for news page, and some news has content long and in this case I want to create hyper link but in case the length small no need for the link, the code that I used: 我正在尝试根据数据库字段的特定值创建超级链接,它用于新闻页面,并且某些新闻的内容很长,在这种情况下,我想创建超级链接,但是如果长度很小,则不需要链接,我使用的代码:

<asp:Label ID="lblContent" runat="server" 
                        Text='<%# string.Format("{0}",Eval("New_Content").ToString().Length>150? <a href> Eval("New_Content").ToString().PadRight(150).Substring(0,150).TrimEnd() + " ..." </a>:Eval("New_Content")) %>' >
                    </asp:Label>

but there is error, so can I have some help? 但是有错误,我可以帮忙吗?

I am trying to create hyper link 我正在尝试创建超级链接

Well why not use a <asp:HyperLink /> control then? 那么为什么不使用<asp:HyperLink />控件呢?

Also don't string use Substring() to reduce the length of the text and add the ... at the end, just use css. 也不要使用Substring()来缩短文本的长度,并在末尾添加... ,而只需使用CSS。

eg 例如

<asp:HyperLink ID="hlContent" runat="server" CssClass="trimme" 
                Text='<%# Eval("New_Content").ToString() %>'></asp:HyperLink>

Then add a css class called trimme 然后添加一个名为trimme的CSS类

a.trimme{
  display: block;  
  width: 150px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

Take a look at this example 这个例子

The code you had was almost correct, it just seems that you are missing some quotes: 您所拥有的代码几乎是正确的,似乎您缺少一些引号:

<asp:Label ID="lblContent" runat="server" 
    Text='<%# String.Format("{0}", Eval("New_Content").ToString().Length > 150 ? "<a href='" + Eval("Link_Href") + Eval("New_Content").ToString().PadRight(150).Substring(0, 150).TrimEnd() + "'>...</a>" : Eval("New_Content")) %>' >
</asp:Label>

The text in an ASP Label is output raw to the response stream, so you can just write standard HTML, but it does need to be in quotes as you are building a new string object. ASP标签中的文本将原始输出到响应流,因此您可以只编写标准HTML,但是在构建新的字符串对象时,它确实需要用引号引起来。

I got the solution using LastIndexOf() as: 我使用LastIndexOf()作为解决方案:

<asp:Label ID="lblContent" runat="server" CssClass="nostyle" 
                        Text='<%# string.Format("{0}",Eval("New_Content").ToString().Length>150?string.Format("<a href=news.aspx?page=3#{0}>{1}</a>",Eval("New_Id"),string.Format("{0} {1}",Eval("New_Content").ToString().PadRight(150).Substring(0,Eval("New_Content").ToString().PadRight(150).Substring(0,150).LastIndexOf(" ")>-1 ? Eval("New_Content").ToString().PadRight(150).Substring(0,150).LastIndexOf(" "): 150).ToString(), " ...")):Eval("New_Content")) %>' >
                    </asp:Label>

Thank you all, you gave me good ideas 谢谢大家,你给了我好主意

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM