The combination of Razor and JavaScript code
Mixing Razor and JavaScript code is a very useful technique in ASP.NET Core applications. A common scenario is when you need to generate dynamic data from C# code and pass it to a JavaScript array.
One way is to use inline snippets and <c>
and </c>
tags, as you mentioned in your question:
<code class="language-csharp"> var data = []; <c#>@foreach (var r in Model.rows) {#> data.push([ <c#>@r.UnixTime#> * 1000, <c#>@r.Value#> ]); <c#>}#></code>
However, there is a simpler and more straightforward way using the <text>
tag:
<code class="language-csharp"> var data = []; @foreach (var r in Model.rows) { <text> data.push([ @r.UnixTime * 1000, @r.Value ]); </text> }</code>
<text>
tag allows you to embed any C# code as plain text into HTML or JavaScript code. This approach is more concise and easier to read, especially when working with longer pieces of code.
When using the <text>
tag, it is important to note that any newlines or spaces in the C# code will be preserved in the generated JavaScript code. If you do not need to preserve these newlines or spaces, you can use the String.Join
statement or other string manipulation techniques to format the output.
The above is the detailed content of How Can I Efficiently Combine Razor and JavaScript to Pass C# Data to a JavaScript Array?. For more information, please follow other related articles on the PHP Chinese website!