如何在后端获取HtmlControl对象的HTML

时间:2010-04-23 20:10:11

标签: c# asp.net

我有一小段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>

有任何想法或建议吗?

3 个答案:

答案 0 :(得分:3)

这是我过去用来获取控件呈现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>

答案 1 :(得分:1)

以下示例可用于扩展任何HtmlControl以使用Render()方法:

public static string Render(this HtmlAnchor TheAnchor)
{
    StringWriter sw = new StringWriter();
    HtmlTextWriter htmlWriter = new HtmlTextWriter(sw);
    TheAnchor.RenderControl(htmlWriter);
    return sw.ToString(); 
}

答案 2 :(得分:0)

是否应该有一个Render方法强制它发出自己的HTML?