Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The problems is that you cannot have a closing <code>&lt;/script&gt;</code> tag inside a JavaScript string literal because the browser interprets it as then end of the script block. See also: <a href="https://stackoverflow.com/questions/1659749/script-tag-in-javascript-string">Script tag in JavaScript string</a></p> <p>There is no builtin function in Asp.Net what could handle it on the server side you before outputting your generated script you need to replace the <code>&lt;/script&gt;</code> to something else:</p> <pre><code>&lt;script type="text/javascript"&gt; $(document).ready(ko.applyBindings(new MyProfileVm(@Html.Raw( JsonConvert.SerializeObject(Model, new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver() }).Replace("&lt;/script&gt;", "&lt;/scripttag&gt;") )))); &lt;/script&gt; </code></pre> <p>Of course if you will need this in multiple place you can move this logic into a helper/extension method, like:</p> <pre><code>public static class JavaScriptExtensions { public static string SerializeAndEscapeScriptTags(this object model) { return JsonConvert.SerializeObject(model, new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver() }).Replace("&lt;/script&gt;", "&lt;/scripttag&gt;"); } } </code></pre> <p>And use it with:</p> <pre><code>@using YourExtensionMethodsNamespace &lt;script type="text/javascript"&gt; $(document).ready(ko.applyBindings(new MyProfileVm(@Html.Raw( Model.SerializeAndEscapeScriptTags())))); &lt;/script&gt; </code></pre> <p>And on the JavaScript side in your Knockout viewmodel you need to replace back the <code>&lt;/script&gt;</code> tag before the usage:</p> <pre><code>var MyProfileVm = function(data) { //... this.aboutMe = ko.observable( // you need `"&lt;/scr"+ "ipt&gt;"` because of the above mentioned problem. data.aboutMe.replace(/&lt;\/scripttag&gt;/g, "&lt;/scr"+ "ipt&gt;")); } </code></pre> <p>Of course you can also create a helper function for this, like:</p> <pre><code>function fixScriptTags(data) { for(var prop in data) { if (typeof(data[prop]) == "string") { data[prop] = data[prop].replace(/&lt;\/scripttag&gt;/g, "&lt;/scr"+ "ipt&gt;"); } //todo check for complex property values and call fixScriptTags recursively } return data; } </code></pre> <p>And use it with:</p> <pre><code>ko.applyBindings(new ViewModel(fixScriptTags(data))); </code></pre> <p>Demo <a href="http://jsfiddle.net/SG3nM/" rel="nofollow noreferrer">JSFiddle</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload