Using RenderControl method to generate Html


This article demonstrates how to generate perfect HTML using the RenderControl method of server controls. The Html code is generated without makeing any server-side state or view state.
/// <summary>
/// This method demonstrates how to show Html output of a Server Control
/// </summary>
private void ShowHtml()
{
  // Create the in-memory objects that will catch the rendered output.
  StringWriter writer = new StringWriter();
  HtmlTextWriter output = new HtmlTextWriter(writer);

  // Render the control to an in-memory string.
  var control = new HyperLink();
  control.NavigateUrl =
@”http:\asghar.panahy.com”;
  control.Text =
“Asghar Panahy”;
  control.Target =
“_blank”;
  control.ToolTip =
“Demostration”;

  control.RenderControl(output);

  // Display the HTML (and encode it properly so that
  // it appears as text in the browser).
  lblHtml.Text = “The HTML for LinkWebControl1 is<br /><blockquote>”
               + Server.HtmlEncode(writer.ToString()) +
“</blockquote>”;
}

The output of this codewill be reading what you would ecpect in the Html code behind.
Notice that skipping the Server.HtmlEncode call will put the generated html as a link into the page.

Author: Pouya Panahy

Microsoft certified DevOps engineer with passion in analysing, designing and implementing solutions for Azure Cloud with hands-on experience in security and quality assurence.

Leave a Reply