2

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?

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Exactly what I was looking for both <text></text> and '@:' prefix work.
0
@{
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

1 Comment

I think this is the opposite of what the OP is asking about

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.