views:

15

answers:

1

Does anyone have any idea how I can intercept the HTML of a page and stop it getting rendered back to the client?

I've tried the following, in a controller method:

var writer = new StringWriter();
var response = new HttpResponse(writer);
var context = new HttpContext(existingContext.Request, response) { User = existingContext.User };            
System.Web.HttpContext.Current = context;

//The method controller method returning an ActionResult for the page I want to render
var ViewResult = ControllerMethod();
ViewResult.ExecuteResult(this.ControllerContext);
string html = writer.ToString();

I think that at this point, the html string should have the HTML of the page that would have been rendered. As it stands, the html variable is an empty string. I suspect that this is because setting the System.Web.HttpContext.Current doesn't affect the controller's HTTP context. Is this a likely cause, and if so is there an approved way of setting the context given that the property is readonly?

I'm trying to render a page to PDF by capturing the raw HTML being created and passing it to a third party component. The controller action containing the above code will then take the raw HTML and convert it to PDF, then return that.

+2  A: 

Use the following to render a view to a string - which can then be passed to your PDF generator

string RenderViewToString(string viewName, object model, string masterName)
{
    if (string.IsNullOrEmpty(viewName))
        viewName = ControllerContext.RouteData.GetRequiredString("action");

        ViewData.Model = model;

        using (StringWriter sw = new StringWriter())
        {
            ViewEngineResult viewResult = ViewEngines.Engines.FindView(ControllerContext, viewName, masterName);

            ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);

            viewResult.View.Render(viewContext, sw);

            return sw.GetStringBuilder().ToString();
        }
    }
Clicktricity
Looks promising thanks - I'll give that a go!
Jon Artus