Home > Web Front-end > JS Tutorial > body text

How to Blend Razor and Javascript Code Within a Script Tag?

Susan Sarandon
Release: 2024-10-26 10:38:30
Original
623 people have browsed it

How to Blend Razor and Javascript Code Within a Script Tag?

Mixing Razor and Javascript Code

Mixing Razor and Javascript code can be a stumbling block for developers. One common challenge arises when trying to declare C# code within a Javascript block.

Question:

How can I effectively combine Razor and Javascript code to achieve something like this?

<script type="text/javascript">
  var data = [];

  <c#>@foreach (var r in Model.rows) {</c#>
      data.push([ <c#>@r.UnixTime</c#> * 1000, <c#>@r.Value</c#> ]);
  <c#>}</caption>
</script>
Copy after login

Answer:

To achieve this mixing, the solution lies in using the element. By encapsulating the C# code within tags, you can smoothly transition between Javascript and Razor syntax.

<script type="text/javascript">
  var data = [];

  @foreach (var r in Model.rows)
  {
    <text>
      data.push([ @r.UnixTime * 1000, @r.Value ]);
    </text>
  }
</script>
Copy after login

The above is the detailed content of How to Blend Razor and Javascript Code Within a Script Tag?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!