Watson
Watson

Reputation: 1425

Convert Razor View to string with JavaScript rendering

These answers render a Razor view to a string, but do not execute scripts in the rendered HTML:

Result of rendering a Razor view to a string:

<body>
    <div id="Test"></div>
    <script type="text/javascript">      
    document.getElementById("Test").innerHTML = "whatever";
    </script>
</body>

Ideally the result would instead be:

  <body>
    <div id="Test">whatever</div>
    <script type="text/javascript">      
    document.getElementById("Test").innerHTML = "whatever";
    </script>
  </body>

Is there any way to get JavaScript to be evaluated when rendering a Razor view on the server?

Upvotes: 1

Views: 934

Answers (1)

Nate Barbettini
Nate Barbettini

Reputation: 53600

Razor is, at the end of the day, a string templating engine. It doesn't actually know much about HTML documents, but it's good at evaluating templates.

Razor is ignoring your JavaScript code because:

  • It isn't building a Document Object Model (DOM) like a browser does
  • It doesn't have a JavaScript interpreter to execute JavaScript code

You would need both of those in order to achieve your ideal result. That's beyond Razor; it's really a job for a full-fledged browser.

I haven't used it myself, but I'd look into the Puppeteer Sharp library. Using that, or a similar library, you can take any arbitrary HTML + JavaScript, evaluate it like a browser does, and then capture the resulting document to get the output you need.

Upvotes: 1

Related Questions