我有一小段C#代码,如下所示:
HtmlGenericControl titleH3 = new HtmlGenericControl("h3");
titleH3.Attributes.Add("class", "accordion");
HtmlAnchor titleAnchor = new HtmlAnchor();
titleAnchor.HRef = "#";
titleAnchor.InnerText = "Foo Bar";
titleH3.Controls.Add(titleAnchor);
我想要的是一种返回看起来像这样的字符串的方法:
<h3 class="accordion"><a href="#">Foo Bar</a></h3>
有什么想法或建议吗?
最佳答案
这是我过去用来提前获取控件的呈现HTML的方法(请确保包含System.IO
):
protected string ControlToHtml(Control c)
{
StringWriter sw = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(sw);
c.RenderControl(htmlWriter);
return sw.ToString();
}
为您的测试用例返回以下内容:
<h3 class="accordion"><a href="#">Foo Bar</a></h3>
关于c# - 如何在后端获取HtmlControl对象的HTML,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2701681/