我开发了一个自定义用户控件。对于特定需要,我必须从其中的usercontrol获取html生成并仅在页面的正文中显示它。
我认为可能会重载RenderControl(HtmlTextWriter writer),但我不知道如何。
由于
答案 0 :(得分:2)
您可以在内存中渲染控件,将其放在字符串上,然后按照您的说法在页面的某处打印此字符串。下面是加载控件并将其呈现在内存中的代码,然后将结果放在字符串上。
// load the control
var oTesto = Page.LoadControl("Testo.ascx");
// here you need to run some initialization of your control
// because the page_load is not loading now.
// a string writer to write on it
using(TextWriter stringWriter = new StringWriter())
{
// a html writer
using(HtmlTextWriter GrapseMesaMou = new HtmlTextWriter(stringWriter))
{
// now render the control inside the htm writer
oTesto.RenderControl(GrapseMesaMou);
// here is your control rendered output.
strBuild = stringWriter.ToString();
}
}
要捕获控件的渲染,您可以使用Render:
protected override void Render(HtmlTextWriter writer)
{
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
// now the control is inside the htmlWriter as final rendered text
base.Render(htmlWriter);
// here is how to make the control render itself
// base.Render(writer);
}
将渲染放置在控件类中。