Razor: Why is my variable not in scope

2019-03-17 18:48发布

@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?

标签: c# razor
2条回答
家丑人穷心不美
2楼-- · 2019-03-17 19:09

In Razor 3.2.3 it seems the variable declared in @functions need to be declared static. Seems unfortunate. Please correct me if there is an alternative way.

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

@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)
   }
}
查看更多
▲ chillily
3楼-- · 2019-03-17 19:14

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.

查看更多
登录 后发表回答