Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a razor for loop be used in a javascript script tag?

The error generated is "Conditional Compilation is turned off".

Conditional Compilation hack from MSDN is prevalent but fails.

There are several questions like this one: Conditional Compilation is turned off in Razor?

They all point to the answer of:

/*@cc_on @*/

From the article seen here at the MSDN:

http://msdn.microsoft.com/en-us/library/5y5529x3(v=vs.90).aspx

However, this hack is pretty fail or I seem to fail at implementing it. The trailing @* causes the remaining code in the .cshtml file to become commented out. Moreover, @cc_on gives an error "cc_on does not exist in the current context".

Here is a piece of code to test in a .cshtml file:

<script type="text/javascript">
 @for(int i = 0; i < 5; i++)
 {
    document.write(@i);
 }
</script>

Which will cause the "Conditional Compilation is turned off" message. Attempting to insert the workaround in there will cause various other messages such as "cc_on" does not exist in the context", "expected ,", or "expected ;", or "expected )" from the for loop.

How can a razor for loop be used in a javascript script tag?

like image 863
Travis J Avatar asked Jul 02 '12 23:07

Travis J


People also ask

Can you use JavaScript with razor?

You can call JavaScript methods from the Blazor pages with the help of JavaScript Interop by injecting the dependency IJSRuntime into the razor page. Then refer the script in the HTML page of the blazor application. Check this link for more information.

How does for loop work in JavaScript?

A for loop repeats until a specified condition evaluates to false. The JavaScript for loop is similar to the Java and C for loop. When a for loop executes, the following occurs: The initializing expression initialExpression , if any, is executed.

Can we write for loop in JavaScript?

JavaScript supports different kinds of loops: for - loops through a block of code a number of times. for/in - loops through the properties of an object. for/of - loops through the values of an iterable object.


1 Answers

Try surrounding your js with <text></text>

<script type="text/javascript">
 @for(int i = 0; i < 5; i++)
 {
    <text>var that = this;</text>
 }
</script>
like image 143
Kyle Trauberman Avatar answered Sep 18 '22 23:09

Kyle Trauberman