TMC
TMC

Reputation: 8154

Confused by variable scope when mixing Javascript and Razor in ASP.NET MVC3

I have some code that is failing due to an error:

The name 'foo' does not exist in the current context 

It's due to a variable scope issue that I'm confused about. I thought that this should work:

var foo = "<ul>";

@for (int i = 0; i < 10; i++)
{
    foo += "<li>bar</li>";
}
foo += "</ul>";

The Razor syntax should invoke the for loop and the variable foo would still be in scope in terms of the javascript because by the time the browser interprets the code, the razor syntax is essentially invisible.

However, the error message I'm getting is from the compiler so somehow the C# is trying to reference foo. What am I missing and how do I modify the code so that I get the proper javascript code outputted so it concatenates <li>bar</li> like I'm attempting to do?

Upvotes: 2

Views: 1419

Answers (2)

COLD TOLD
COLD TOLD

Reputation: 13599

@{
var foo = "<ul>";

for (int i = 0; i < 10; i++)
{
    foo += "<li>bar</li>";
}
foo += "</ul>";

}

or this

@var foo = "<ul>";

@for (int i = 0; i < 10; i++)
{
    foo += "<li>bar</li>";
}
foo += "</ul>";

now this whole aspect is considered razor including the var foo

Upvotes: 0

SLaks
SLaks

Reputation: 887777

The contents of a code block, such as a for loop, are assumed to be server-side code.

You need to explicitly tell Razor that it's markup using the <text> special tag.

Upvotes: 5

Related Questions