Is it possible to save an MVC Razor view into an actual html file
Asked Answered
C

1

10

We are building an MVC app that creates physical HTML pages. The app currently creates the pages dynamically using the normal MVC/Razor approach.

Rather than re-creating the output programatically to a file, is there anyway to grab the result built by razor and save it to a file?

Thanks so much!

Chivalric answered 15/3, 2014 at 0:48 Comment(0)
U
14

you can render the view to string, then save the string in a file ...

public string RenderViewToString(string viewName, object model)
{
  ViewData.Model = model;
  using (var sw = new StringWriter())
  {
    var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
    var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
    viewResult.View.Render(viewContext, sw);
    viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
    return sw.GetStringBuilder().ToString();
  }
}
Underrate answered 15/3, 2014 at 2:44 Comment(1)
Sorry for the delay. I just did not get a chance to test this until now. Seems to be working well. Thanks so much!Chivalric

© 2022 - 2024 — McMap. All rights reserved.