Welcome to AspAdvice Sign in | Join | Help

Render User Control as String Template

Scott Guthrie has a great example of how to use an ASP.NET user control as a template which one can dynamically bind to data and then pull the results out as a string.  One place this is useful is in AJAX scenarios in which you want to replace the contents of a region of the page with the rendered output of a user control.  I'm using this very successfully in Lake Quincy Media AdSignia for our dashboard pages, to enable me to load the page instantly and then dynamically fetch the individual charts and dashboard controls asynchronously via ASP.NET AJAX.  I'll be writing up a full article on this whole process soon, but for now I just want to show my version of ScottGu's ViewManager class, which has been modified to use generics and interfaces to make it a bit more cohesive (it also no longer uses reflection).  The user control must now implement a generic interface, IRenderable<T>, where T is the data it expects to be passed in.

    public class ViewManager
    {
        public static string RenderView<D>(string path, D dataToBind)
        {
            Page pageHolder = new Page();
            UserControl viewControl = (UserControl) pageHolder.LoadControl(path);
            if(viewControl is IRenderable<D>)
            {
                if (dataToBind != null)
                {
                    ((IRenderable<D>) viewControl).PopulateData(dataToBind);
                }
            }
            pageHolder.Controls.Add(viewControl);
            StringWriter output = new StringWriter();
            HttpContext.Current.Server.Execute(pageHolder, output, false);

            return output.ToString();
        }
    }

    public interface IRenderable<T>
    {
        void PopulateData(T data);
    }
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

 

A user control implementing this interface might look like this:

    public partial class View_PublisherEarningsChart : System.Web.UI.UserControl, IRenderable<DataSet>
    {
        protected DataSet chartData;
        protected void Page_Load(object sender, EventArgs e)
        {
            BindPublisherEarningsChart();
        }
        public void BindPublisherEarningsChart()
        {
          // Bind chart here
        }

        #region IRenderable<DataTable> Members
        public void PopulateData(DataSet data)
        {
            chartData = data;
        }
        #endregion
    }

With this approach, it's easy to separate the data access from the rendering, and is very similar to the Model-View-Controller (MVC) approach that is getting a lot of press time lately in the ASP.NET world.  Again, I'll show the full dynamic loading async stuff very soon in a full article.

Published Friday, October 19, 2007 1:27 PM by ssmith
Filed under: , ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: Render User Control as String Template

Nice article. Another place this is usefull is for sending emails.

Saturday, October 20, 2007 9:06 PM by Chris Mizer

# re: Render User Control as String Template

good one, this will be very much useful t load data on-demand...

Tuesday, October 23, 2007 4:20 AM by Yoganand

# re: Render User Control as String Template

good extension of scott gu's code.

Can you use this code from outside iis?

How does one create a Server instance for running Server.Execute not within IIS?

We launch the majority of emails from a windows service and have considered using code smith or another commercial templater to process html emails. However, this solution is waaay better, but may not been accessible outside of IIS.

Wednesday, November 07, 2007 1:14 PM by Vijay Santhanam

# re: Render User Control as String Template

Vijay,

 You can probably mock the HttpContext by using the one available in Plasma (http://codeplex.com/plasma) instead.  I'm not certain it has support for Server.Execute (it's likely it does not) but that is where I would look to do what you're asking.  Add it as a feature request in the project if it's not there.

Friday, November 16, 2007 1:56 AM by ssmith

# re: Render User Control as String Template

cool, done very cleverly, helped me a lot

Friday, November 16, 2007 10:03 AM by Jay

# re: Render User Control as String Template

This is a great post. However, I must be missing something simple. I get an error om the "HttpContext.Current.Server.Execute(page, writer, false); " line whenever I place an asp.net control into my .ascx page and try to call it using web services in my main page. When I take the controls off, it works fine. Please Help. Thanks in advance!

Friday, February 22, 2008 11:39 AM by Rich Smith

# re: Render User Control as String Template

Hi Smith,

In my application, i try to load ascx file using

HttpContext.Current.Server.Execute

I use Icallbackeventhandler to load page asynchronously

but i get error.....

Error executing child request for handler ‘System.Web.UI.Page’.

When i make control read as normal html controls with runat="server"...it works

for example

<asp:textbox> i change it to <input type="text" runat="server"> -- this works,

but for controls like CalendarExtender i have the problem Error executing child request ,

is there a workaround for this? kindly let me know

My requirement is to load ascx page(having web controls),  convert it to string and pass it to GetCallBackResult()

Thanks

Monday, May 12, 2008 11:40 AM by Paul

# re: Render User Control as String Template

A nice improvement over ScottGu's technique. A minor correction in code would be to use "as" operator

Friday, May 23, 2008 5:06 AM by Sathya

# re: Render User Control as String Template

A nice improvement over ScottGu's technique. A minor change in code would be to use "as" operator instead of "is" operator:

<p class="csharpcode">

IRenderable<D> controlToRender = viewControl as IRenderable<D>;

if(controlToRender != null)

           {

               if (dataToBind != null)

               {

                   controlToRender.PopulateData(dataToBind);

               }

           }

</p>

Friday, May 23, 2008 5:12 AM by Sathya

# Rendering ASP .Net user controls for AJAX callbacks

Rendering ASP .Net user controls for AJAX callbacks

Sunday, June 29, 2008 3:55 AM by Andrei Butnaru's blog

# re: Render User Control as String Template

how can i get my HD back - i think im being controlle with a rootkit or something...

email - sputnik1121@yahoo.com

Sunday, July 20, 2008 12:14 AM by sputnik

Leave a Comment

(required) 
required 
(required) 
Enter the code you see below