How to get html rendered from an ActionResult in ASP.NET MVC Controller [closed]

0

I'm doing a PDF export where the content of the document is the html of a Rendered View.

How do I do this?

    
asked by anonymous 20.07.2018 / 00:25

1 answer

0

I've used the solution from this other question (in English):

public string RenderRazorViewToString(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();
  }
}


public ActionResult RenderViewToString()
{
    var model = new MeuModelo()
    {
        Nome = "William John",
        Endereco = "123, rue des Canadiens",
        Telefone = "(555) 555-7777"
    };

    string html = RenderViewToString(
            "~/views/Etiqueta.cshtml",
            model);


    CreatePdf(html);

    return View();
}

How it works:

  • The ViewEngines.Engines.FindPartialView Method (if you want to render a View, use the FindView method) creates an instance of your partialview in viewResult
  • An instance of ViewContext is created. This is where the model and tempdata are provided to the View.
  • The Render method renders HTML rendering and uses the StringWriter to create a String Builder that will receive the Render result.
  • 20.07.2018 / 00:40