c# – How to convert a view to a string in the controller?


I would like to convert this view to string and have the value in string in my controller

The problem is that I would like it to run a script snippet that is in this view

The current method I have, it just converts, without executing the script that is in this view currently looks like this:

  public static string PartialViewToString(this Controller controller, string viewName, object model)
      if (string.IsNullOrEmpty(viewName))
        viewName = controller.ControllerContext.RouteData.GetRequiredString("action");

      controller.ViewData.Model = model;

      using (StringWriter stringWriter = new StringWriter())
        ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
        ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, stringWriter);
        viewResult.View.Render(viewContext, stringWriter);
        return stringWriter.GetStringBuilder().ToString();

In my controller I call:

var htmlString = helper.PartialViewToString(this,"NomeView",model);


Scripts in the view are only executed on the client side – in the browser – after the HTML has been generated and sent to the client.

You will need another view without javascript to generate the PDF. There are even javascript engines to run on the server side, but I think this would be unnecessary, it would be considered a "hack", and would no doubt affect server performance.

Scroll to Top