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)?