2

Is it possible to get the resulting HTML that is outputting from an action via code?

mrblah
  • 99,669
  • 140
  • 310
  • 420
  • 3
    check this : http://stackoverflow.com/questions/483091/render-a-view-as-a-string –  Oct 01 '09 at 12:54

3 Answers3

0

Check out MvcIntegrationTestFramework

0

To be specific on why you would look at MvcIntegrationTestFramework.

It makes saves you writing your own helpers to stream result and is proven to work well enough. I'd assume this would be in a test project and as a bonus you would have the other testing capabilities once you've got this setup. Main bother would probably be sorting out the dependency chain.

 private static readonly string mvcAppPath = 
     Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory 
     + "\\..\\..\\..\\MyMvcApplication");
        private readonly AppHost appHost = new AppHost(mvcAppPath);

    [Test]
    public void Root_Url_Renders_Index_View()
    {
        appHost.SimulateBrowsingSession(browsingSession => {
            RequestResult result = browsingSession.ProcessRequest("");
            Assert.IsTrue(result.ResponseText.Contains("<!DOCTYPE html"));
        });
}
dove
  • 20,469
  • 14
  • 82
  • 108
0

Here is an example of how I have done it in Razor syntax. I needed to get the html from one action as a string in another action (to the render as a pdf)

 ViewResult viewResult = ActionYouWhatHtmlFrom(id);

       using (var writer = new StringWriter())
       {
           ViewEngineResult result = ViewEngines
                     .Engines
                     .FindView(ControllerContext,
                               viewResult.ViewName, "_YourLayout");


           var viewPath = ((RazorView)result.View).ViewPath;
           var layoutPath = ((RazorView) result.View).LayoutPath;

           var view = new RazorView(ControllerContext, viewPath, layoutPath, true, null);
           var viewCxt = new ViewContext(
                               ControllerContext,
                               view,
                               viewResult.ViewData,
                               viewResult.TempData, writer);
           viewCxt.View.Render(viewCxt, writer);
ctrlalt313373
  • 3,935
  • 7
  • 36
  • 40