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

最佳答案

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的另一个答案的帮助下编写的一段代码中复制而来的,非常适合我。

09-06 05:11