Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor: Why is my variable not in scope

Tags:

@inherits umbraco.MacroEngines.DynamicNodeContext
@using System.Collections;

@{ List<string> qa = new List<string>(); } //this is not defined in the recursive helper below

@helper traverseFirst(dynamic node){
   var items = node.Children.Where("umbracoNaviHide != true");
   foreach (var item in items) {
     foreach(var subItem in item.Descendants()) {
        if(subItem.Id == Model.Id)
        {
           qa.Add();
           break;
        }
     }
     @traverseFirst(item)
   }
}

@traverseFirst(@Model.AncestorOrSelf("Book"))

The variable qa canot be accessed in the recursive helper. Is there a way around this?

like image 426
Luke101 Avatar asked May 20 '11 08:05

Luke101


People also ask

What happens when a variable runs out of scope?

Nothing physical happens. A typical implementation will allocate enough space in the program stack to store all variables at the deepest level of block nesting in the current function. This space is typically allocated in the stack in one shot at the function startup and released back at the function exit.

How do you declare a variable in a razor?

To declare a variable in the View using Razor syntax, we need to first create a code block by using @{ and } and then we can use the same syntax we use in the C#. In the above code, notice that we have created the Code block and then start writing C# syntax to declare and assign the variables.

What determines the scope of a variable?

In simple terms, scope of a variable is its lifetime in the program. This means that the scope of a variable is the block of code in the entire program where the variable is declared, used, and can be modified.

Can we declare a variable in different scopes with different data types?

No, you cannot redefine a variable with different types within the same scope.


1 Answers

Define the variable in a @functions section.

The normal @{ places your code in some method body. Use @functions to define class members.

@functions{ List<string> qa = new List<string>(); } 

More reading on this matter: SLaks Dissecting razor series.

like image 83
GvS Avatar answered Sep 17 '22 11:09

GvS