1

I need to get the HTML of a Razor view as a string in an ASP.NET MVC 5 application. I can almost do this with no problems but there are some HTML elements within the view that are created by JavaScript, which are not part of the string returned by the code below:

private string RazorToHtml(string viewName)
{
    using (StringWriter sw = new StringWriter())
    {
        var viewResult = ViewEngines.Engines.FindView(ControllerContext, viewName, "");
        var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
        viewResult.View.Render(viewContext, sw);
        var html = sw.GetStringBuilder().ToString();
        return html;
    } 
}

This method looks for the view by name and renders the Razor to HTML into a StringWriter.

The issue with this is that any Javascript on the page has not been executed.

How can I execute the scripts and then get the "final" HTML (including the elements created by the JS)?

Samuel Pearsall
  • 445
  • 1
  • 5
  • 11
  • Possible duplicate of [What is server side rendering of javascript?](http://stackoverflow.com/questions/16173469/what-is-server-side-rendering-of-javascript) – esiprogrammer Dec 13 '16 at 11:01
  • @esiprogrammer I'm not asking what server-side rendering of javascript is, more _how_ can I (or if I can) get html that is created by JavaScript to be generated as part of server-side Razor to HTML conversion. – Samuel Pearsall Dec 13 '16 at 11:06
  • 1
    You can't with Razor, it is a rendering engine that creates output using solely MVC views and viewmodels, for a browser or other kind of webclient. So it can render, but it can't interpret or execute. To go this way you need to incorporate a webclient (which I never did, maybe someone else knows). – Peter B Dec 13 '16 at 11:06
  • @PeterB thanks, I wanted to try to do this without using a tool that creates a headless browser, as it seems a bit overkill just to get a bit of html... but it's beginning to look like that's the way I'm going to have to go! Thanks for your help. – Samuel Pearsall Dec 13 '16 at 11:10

0 Answers0