我正在从代码后面的某个网页添加一些内容.当我想在一些文本后添加一个中断时,我尝试这样做:
pDoc.Controls.Add(New Label With {.Text = "whatever"}) pDoc.Controls.Add(New HtmlGenericControl("br"))
,其中pDoc是我正在添加内容的Panel.但它在最终的HTML中添加了两个br标签.
我这样避免这种行为:
pDoc.Controls.Add(New Label With {.Text = "whatever" & "<br />"})
无论如何,我很好奇,我想知道为什么
pDoc.Controls.Add(New HtmlGenericControl("br"))
这样做.我也认为我的方法不太花哨.
问候,
解决方法
@H_403_21@ 经过一些测试后看起来原因是HtmlGenericControl不支持自闭.在服务器端,HtmlGenericControl(“br”)被视为:<br runat="server"></br>
没有< / br> HTML中的标记,因此浏览器显示它,因为有两个< br />标签.很好的方法是这样创建HtmlGenericSelfCloseControl(抱歉C#代码,但在VB.NET中重写这个应该没有问题):
public class HtmlGenericSelfCloseControl : HtmlGenericControl { public HtmlGenericSelfCloseControl() : base() { } public HtmlGenericSelfCloseControl(string tag) : base(tag) { } protected override void Render(HtmlTextWriter writer) { writer.Write(HtmlTextWriter.TagLeftChar + this.TagName); Attributes.Render(writer); writer.Write(HtmlTextWriter.SelfClosingTagEnd); } public override ControlCollection Controls { get { throw new Exception("Self closing tag can't have child controls"); } } public override string InnerHtml { get { return String.Empty; } set { throw new Exception("Self closing tag can't have inner content"); } } public override string InnerText { get { return String.Empty; } set { throw new Exception("Self closing tag can't have inner text"); } } }
而是使用它:
pDoc.Controls.Add(New Label With {.Text = "whatever"}) pDoc.Controls.Add(New HtmlGenericSelfCloseControl("br"))
作为一个更简单的替代方法(如果您引用了Page),您可以尝试使用Page.ParseControl:
pDoc.Controls.Add(New Label With {.Text = "whatever"}) pDoc.Controls.Add(Page.ParseControl("br"))