How to get rendered html from an Actionresult in the ASP.NET MVC Controller

Asked

Viewed 57 times

0

I am performing a PDF export where the document content is the html of a Rendered View.

How do I do it?

1 answer

1


I used the solution of 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:

  1. The Viewengines.Engines.Findpartialview Method (if you want to render a View, use the Findview method) creates an instance of your partialview in viewResult
  2. an instance of Viewcontext is created. It is at this point that the template and tempdata are provided to the View.
  3. Render renders in HTML and uses Stringwriter to create a String Builder that will receive the result of Rendering.
  • It worked out, thank you very much Willian :) I had seen this, but I wasn’t getting it, apparently the error was in the viewname, I was putting only the name of the view and not way.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.