Home >Backend Development >C++ >How to Properly Mix Razor and JavaScript Code in Script Tags?

How to Properly Mix Razor and JavaScript Code in Script Tags?

Barbara Streisand
Barbara StreisandOriginal
2025-01-19 10:57:10619browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn