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
Release: 2025-01-19 10:57:10
Original
617 people have browsed it

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>
Copy after login

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>
Copy after login
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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template