Question

I need to get the HTML of a user control.

At the moment I am using below code.

// 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.

Can you please explain how I can achieve this using the approach 1 So that I dont have to hard code the virtual path of the control.

I have also tried the other overload of the 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 :(
Was it helpful?

Solution

bshould be a System.IO.StringWriter. Your code in approach 1 should look like this:

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();

This is copied from a piece of code I've written with help of another answers here in SO, and works perfectly for me.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top