I have an ASP.NET MVC view model that I need to pass to a JavaScript function when the page loads, and I'm currently doing that like so:
<script type="text/javascript">
$(window).on("load", function () {
myFunction(@Html.Raw(JsonConvert.SerializeObject(Model)));
});
</script>
In other words, I'm using JSON.NET to serialize the model to JSON, and inserting that (un-encoded) into my <script>
block.
When rendered, the script block ends up looking something like:
<script type="text/javascript">
$(window).on("load", function () {
myFunction({"myProperty": "the property value"});
});
</script>
That works, up to a point. But when my model contains a string property that whose text includes HTML tags *, these confuse the browser into thinking that the <script>
block has ended, and the browser starts rendering the tags embedded in the view model.
- Edit: per the comments, this only happens if there's a
</script>
tag.
For example:
<script type="text/javascript">
$(window).on("load", function () {
myFunction({"myProperty": "<script>...</script>"});
});
</script>
How can I solve this?