How to convert a view to string in the controller?

Asked

Viewed 98 times

3

I’d like to convert that view for string and have the value in string in my controller

The problem is that I’d like her to perform a snippet of script that’s in this view

The current method I have, just converts, without executing the script that’s in this view Currently it is 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();
      }
    }

On my controller I call:

var htmlString = helper.PartialViewToString(this,"NomeView",model);
  • What would be these "scripts"? Javascripts?

  • Why do you need the string view in the controller? That’s a very strange requirement... I’m pretty sure there’s a better way to solve your problem.

  • Hello, yes "scripts" are Avascripts

  • @dcastro, have you seen the "rotary" lib rendering the pdf view ? then, the idea is the same, however I want to store the byte[]

  • Okay, sounds like a valid use case to me. And what would scripts do that was relevant to PDF generation?

  • @dcastro is mounted using template engine in js, using data that comes via json

  • That is, the view that is initially sent to the customer does not contain data, and this data is later obtained via AJAX? In that case, I think you’ll need a different view to generate the PDF, a view created on time with all the necessary data .

  • yes, that’s why I want to capture it in the controller

  • Yes, I think the best thing is to create a view without javascript for the PDF :/ put in the answer

Show 4 more comments

1 answer

1

The 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 that would be unnecessary, would be considered a "hack", and would undoubtedly affect the performance of the server.

Browser other questions tagged

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