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

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

Up vote 1 down vote favorite share g+ share fb share tw.

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 = ""; @for (int I = 0; I bar"; } foo += ""; 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 bar like I'm attempting to do? C# asp. Net-mvc asp.

Net-mvc-3 razor link|improve this question asked Nov 6 '11 at 20:27TMC814424 68% accept rate.

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 special tag.

Thanks! Exactly what I was looking for both and '@:' prefix work. – TMC Nov 6 '11 at 21:26.

{ var foo = ""; for (int I = 0; I bar"; } foo += ""; } or this @var foo = ""; @for (int I = 0; I bar"; } foo += ""; now this whole aspect is considered razor including the var foo.

I think this is the opposite of what the OP is asking about – 32bitkid Nov 6 '11 at 21:11 yes, this is the opposite of what I was asking. – TMC Nov 6 '11 at 21:27.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions