Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local variables don't work in Razor helpers

This code does work inside Razor Views but does NOT work inside custom helpers body and in _Layout.cshtml:

@{ var v = "foo"; }
@v

Error message: "Element v does not exist in current context"

I use just downloaded Visual Web Developer Express 2010.

Can anybody explain this behaviour?

like image 630
xoposhiy Avatar asked Jan 30 '11 17:01

xoposhiy


1 Answers

This code works fine in both views and _layout.cshtml. And as far as helpers are concerned here's the syntax:

@helper MyHelper()
{
    var v = "foo";
    @v    
}
@MyHelper()

This being said declaring local variables and writing C# code in views should be avoided.

like image 132
Darin Dimitrov Avatar answered Nov 05 '22 07:11

Darin Dimitrov