1

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?

Nate Barbettini
  • 51,256
  • 26
  • 134
  • 147
Watson
  • 1,385
  • 1
  • 15
  • 36

1 Answers1

1

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.

Nate Barbettini
  • 51,256
  • 26
  • 134
  • 147