问题描述
我添加从code背后的一些内容,以给定的网页。当我想一些文本后添加一个突破,我尝试这样做,是这样的:
I'm adding some content to a given web page from code behind. When I want to add a break after some text, I try to do that this way:
pDoc.Controls.Add(New Label With {.Text = "whatever"})
pDoc.Controls.Add(New HtmlGenericControl("br"))
,其中PDOC是面板
在我添加的内容。但它增加了两个 BR
标记成最终的HTML。
,where pDoc is the Panel
in which I'm adding the content. But it adds two br
tags into the final HTML.
我已经避免这种情况是这样的:
I've avoid this behaviour this way:
pDoc.Controls.Add(New Label With {.Text = "whatever" & "<br />"})
不过,我很好奇,我想知道为什么。
Anyway, I'm so curious and I want to know why
pDoc.Controls.Add(New HtmlGenericControl("br"))
行事的方式。我也觉得我的做法是不是太花哨。
is acting that way. I also think my approach is not too fancy.
问候,
推荐答案
一些测试它看起来像的原因之后是 HtmlGenericControl
不支持的自动关闭的。在服务器端的 HtmlGenericControl(BR)
被视为:
After some testing it looks like the reason is that HtmlGenericControl
doesn't support self closing. On server side the HtmlGenericControl("br")
is treated as:
<br runat="server"></br>
有没有&LT; / BR&gt;在HTML
标签,所以浏览器显示它作为有两个&LT; BR /&GT;
标记。尼斯出路是创建 HtmlGenericSelfCloseControl
这样的(对不起,C#code,但你应该没有问题,在VB.NET rewritting本):
There is no </br>
tag in HTML, so the browser shows it as there are two <br />
tags. Nice way out of this is to create HtmlGenericSelfCloseControl
like this (sorry for C# code but you should have no issue with rewritting this in 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.ParseControl
:
As a simpler alternative (if you have reference to the Page
) you can try using Page.ParseControl
:
pDoc.Controls.Add(New Label With {.Text = "whatever"})
pDoc.Controls.Add(Page.ParseControl("br"))
这篇关于HtmlGenericControl(QUOT; BR&QUOT;)渲染两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!