简体   繁体   English

将html标记添加到C#中的字符串

[英]Add html tag to a string in C#

I want to add a html tag to a string for styling purpose 我想将html标记添加到字符串中以进行样式设置

ListItem item = new ListItem("abc", "www.http://stackoverflow.com");
blogList.Items.Add(item);

I want to add tag to string "abc". 我想将标签添加到字符串“ abc”。 I looked into HtmlString and HtmlStringWriter but they look too complicated. 我调查了HtmlString和HtmlStringWriter,但它们看起来太复杂了。

Can anyone demonstrate a small piece of working code? 谁能演示一小段工作代码? or any method I can use? 或我可以使用的任何方法?

You can't add html tags in a list item object. 您不能在列表项对象中添加html标签。

You should use a repeater control instead 您应该改用中继器控件

To add a specific css attribute you can use: 要添加特定的css属性,可以使用:

yourobject.Attributes.Add("background-color", "black");

to add a css style already defined in your style sheet you can use: 要添加样式表中已定义的css样式,可以使用:

yourobject.CssClass = "classname";

I'm not sure why you want HTML within a list item's text, as it seems problematic as Gilbert pointed out, but if you just want to dynamically add HTML to your page there are many ways, including using a Label or a Literal. 我不确定为什么要在列表项的文本中添加HTML,正如Gilbert指出的那样,这似乎是有问题的,但是如果您只是想动态地将HTML添加到页面中,则有很多方法,包括使用Label或Literal。 Simply declare an <asp:Literal ID="myLit"..> object on your .aspx page, then within your code source (.cs) file say myLit.Text = "<p>Some HTML</p>"; 只需在.aspx页面上声明<asp:Literal ID="myLit"..>对象,然后在代码源(.cs)文件中说myLit.Text = "<p>Some HTML</p>";

I suggest using Literal 我建议使用文字

markup        
<asp:Literal ID="myLiteral" runat="server"></asp:Literal>  

codebehind    
myLiteral.Text = "<a href='default.aspx'><b>tag here</b></a>";

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

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