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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@Watson Glad to hear it! 👍

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.