我需要获取用户控件的HTML。
目前我正在使用下面的代码。
// Approach 1
HeaderControl hControl = new HeaderControl();
StringBuilder b = new StringBuilder();
HtmlTextWriter h = new HtmlTextWriter(new StringWriter(b));
hControl.RenderControl(h);
string controlAsString = b.ToString();
// controlAsString is "" -- Doesn't work
// ----------------------------------------------
// Approach 2
UserControl uc = new UserControl();
HeaderControl hc = (HeaderControl)uc.LoadControl("~/Views/HeaderControl.ascx");
hControl.RenderControl(h);
string controlAsString = b.ToString();
// controlAsString = "<h3>test data</h3> - Works.
请你解释一下如何使用方法1实现这一目标,这样我就不必硬编码控件的虚拟路径。
我也尝试过uc.LoadControl()
的其他重载UserControl uc = new UserControl();
HeaderControl hControl = (HeaderControl)uc.LoadControl(typeof(HeaderControl), null);
// Header control has a default constructor that takes no parameters
// but no luck :(
答案 0 :(得分:0)
b
应为System.IO.StringWriter
。方法1中的代码应如下所示:
var hControl = new HeaderControl();
var strWriter = new System.IO.StringWriter();
var htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);
hControl.Rendercontrol(htmlWriter);
string ControlAsString = strWriter.ToString();
这是从我在SO中写下的另一个答案的一段代码中复制而来,对我来说非常适合。