using System;
using System.IO;
using System.Web;
using System.Collections.Generic;
namespace MvcContrib.UI
{
/// Renders an Action delegate and captures all output to a string.
public class BlockRenderer
{
private readonly HttpContextBase _httpContext;
public BlockRenderer(HttpContextBase httpContext)
{
_httpContext = httpContext;
}
public partial class HttpResponse
{
public bool UsingHttpWriter { get { return true; } }
}
/// Renders the action and returns a string.
/// The delegate to render.
/// The rendered text.
public string Capture(Action viewRenderer)
{
HttpResponseBase resp = _httpContext.Response;
Stream originalFilter = null;
CapturingResponseFilter innerFilter;
string capturedHtml = "";
if (viewRenderer != null)
{
try
{
resp.Flush();
originalFilter = resp.Filter;
innerFilter = new CapturingResponseFilter(resp.Filter);
resp.Filter = innerFilter;
viewRenderer();
resp.Flush();
capturedHtml = innerFilter.GetContents(resp.ContentEncoding);
}
finally
{
if (originalFilter != null)
{
resp.Filter = originalFilter;
}
}
}
return capturedHtml;
}
}
}