2

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!

Bill Jones
  • 701
  • 4
  • 16
  • 24
  • 1
    Why you dont open in browser and save source as to get all html component..Once it is in browser there will be no razor syntax only plain html,css,script. – Garry Feb 15 '13 at 15:28
  • What are you intending on doing with this HTML? caching the output? If so, it would probably be better to look at caching the data instead. – ChrisBint Feb 15 '13 at 15:30
  • Why do you want to write this to a file? Do what Chris says and look at caching the request – CR41G14 Feb 15 '13 at 15:31
  • I think Bill Jones want to export report data not html ...If this is the case it is a bad idea to export using html as asp.net and c# already gives report export support... – Garry Feb 15 '13 at 15:34
  • Check out this answer and see if it helps [Render a view as a string](http://stackoverflow.com/questions/483091/render-a-view-as-a-string). – Caleb Kiage Feb 15 '13 at 15:43
  • @Garry What export support is built into MVC4? – CR41G14 Feb 15 '13 at 15:55
  • @Bill Jones did you try my answer? – Oliver Mar 14 '13 at 22:59

1 Answers1

1

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();
    }
}
Oliver
  • 8,794
  • 2
  • 40
  • 60