Bill Jones
Bill Jones

Reputation: 701

Getting HTML Generated By ASP.NET MVC View

I'm working on an ASP.NET MVC 4 app. I'm trying to build a report screen that takes a while (~30 seconds) to generate due to the data. What I would like to do is get the HTML that's generated by the view and save it to a text file.

Is there a way to get the HTML generated by a View? If so, how? Please note that my .cshtml file includes some RAZOR. I'm not sure if that plays into this equation or not.

Thank you so much for your help!

Upvotes: 2

Views: 2425

Answers (1)

Oliver
Oliver

Reputation: 9002

I use the following function to do this sort of thing, usually when I want to create email HTML using razor:

public static string RenderViewToString(string viewName, object model, ControllerContext context)
{
    context.Controller.ViewData.Model = model;
    using (var sw = new StringWriter())
    {
        var viewResult = ViewEngines.Engines.FindPartialView(context, viewName);
        var viewContext = new ViewContext(context, viewResult.View, context.Controller.ViewData, context.Controller.TempData, sw);
        viewResult.View.Render(viewContext, sw);
        return sw.GetStringBuilder().ToString();
    }
}

Upvotes: 1

Related Questions