Home >Backend Development >C++ >How to Properly Mix Razor and JavaScript Code in Script Tags?
Mix Razor and JavaScript code in script tags
When mixing Razor and JavaScript code, mixing raw C# statements and JavaScript inside script tags can be tricky. Consider the following scenario:
<code class="language-csharp"> var data = []; @(foreach (var r in Model.rows) { data.push([ r.UnixTime * 1000, r.Value ]); })</code>
The goal is to iterate over a C# collection and push values into a JavaScript array. However, this approach is not feasible due to syntax conflicts.
Solution:
An alternative is to use the @text
directive, which allows you to output raw text without any escaping or HTML encoding:
<code class="language-csharp"> var data = []; @foreach (var r in Model.rows) { <text> data.push([ @r.UnixTime * 1000, @r.Value ]); </text> }</code>The
@text
directive allows raw C# code to be included as part of a JavaScript script, seamlessly combining the two languages within the script tag.
The above is the detailed content of How to Properly Mix Razor and JavaScript Code in Script Tags?. For more information, please follow other related articles on the PHP Chinese website!