有没有办法在代码隐藏中为html字符串创建和呈现asp控件?

时间:2009-11-18 16:31:38

标签: c# .net asp.net html

如何创建新的DropDownList(或任何asp服务器控件),然后将html呈现为C#中的字符串?

1 个答案:

答案 0 :(得分:4)

System.Web.UI.Control有一个RenderControl(HtmlTextWriter)方法,您可以使用该方法将控件的呈现内容作为字符串获取:

using(var sw = new System.IO.StringWriter()) // SW is a buffer into which the control is rendered
using(var writer = new HtmlTextWriter(sw))
{
    myControl.RenderControl(writer);
    return sw.ToString(); // This returns the generated HTML.
}