Home > Article > Web Front-end > How to Seamlessly Combine Razor and JavaScript Code Within a Web Page?
Incorporating both Razor and JavaScript code within the same web page can be a bit tricky. Consider the following sample code:
<code class="html"><script type="text/javascript"> var data = []; @foreach (var r in Model.rows) { data.push([ @r.UnixTime * 1000, @r.Value ]); } </script></code>
This code attempts to create a JavaScript array called data and populate it using a Razor foreach loop. However, it doesn't quite do what we intended.
The Ideal Solution:
Our desired result is to be able to write code that looks something like this:
<code class="html"><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#>}</c#> </script></code>
This code mixes Razor and JS code seamlessly, allowing us to easily iterate through a C# collection and populate our JavaScript array.
The Solution:
To achieve this, we can use plain text sections. Replace the
<code class="html"><script type="text/javascript"> var data = []; @foreach (var r in Model.rows) { <text> data.push([ @r.UnixTime * 1000, @r.Value ]); </text> } </script></code>
Using plain text sections allows us to include arbitrary JS code within our script block, while still utilizing Razor's syntax to access data from the server. Now, our code should behave as intended, populating the data array with values from our C# collection.
The above is the detailed content of How to Seamlessly Combine Razor and JavaScript Code Within a Web Page?. For more information, please follow other related articles on the PHP Chinese website!