代码之家  ›  专栏  ›  技术社区  ›  John Lechowicz

如何获取后端htmlcontrol对象的html

  •  1
  • John Lechowicz  · 技术社区  · 14 年前

    我有一小段这样的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 回复  |  直到 13 年前
        1
  •  3
  •   wsanville    14 年前

    这是我过去用来提前获取控件呈现的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>
    
        2
  •  1
  •   Todd H.    13 年前

    下面是一个示例,您可以使用它来扩展任何htmlcontrol以具有render()方法:

    public static string Render(this HtmlAnchor TheAnchor)
    {
        StringWriter sw = new StringWriter();
        HtmlTextWriter htmlWriter = new HtmlTextWriter(sw);
        TheAnchor.RenderControl(htmlWriter);
        return sw.ToString(); 
    }
    
        3
  •  0
  •   Jeremy    14 年前

    难道不应该有一个渲染方法强制它发出自己的HTML吗?