我需要获取用户控件的 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 :(