Branislav Abadjimarinov's technical blog

How to render asp.net control to string

Posted in C#, ASP.NET, ASP.NET MVC by Branislav Abadjimarinov on 10/28/2009 9:10:00 AM - CST

Every control in ASP.NET inherits from System.Web.UI.Control and have the RenderControl method. When you want to get the html output of the control at any point of the page execution lifecycle you can use the following method.

public string RenderControl(Control ctrl)
{
    StringBuilder sb = new StringBuilder();
    StringWriter tw = new StringWriter(sb);
    HtmlTextWriter hw = new HtmlTextWriter(tw);

    ctrl.RenderControl(hw);
    return sb.ToString();
}

At this point ASP.NET MVC does not have full support for asp.net controls. Using this trick you can render control's html directly on the view using a html helper. While this is good for read-only controls it will not work with controls that require event handling because in ASP.NET MVC by default you are missing  the page lifecycle.

Comments

Trackback  on 12/13/2009 3:04:34 AM - CST

Add Comment

Please enter your name. Please enter a valid email. Please enter a valid website.
Please supply a comment.
© Copyright 2014 Powered by AtomSite 1.3.0.0