Reputation: 1425
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
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:
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