Razor: Why is my variable not in scope

我怕爱的太早我们不能终老 提交于 2019-12-20 17:27:53

问题


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


回答1:


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.




回答2:


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)
   }
}


来源:https://stackoverflow.com/questions/6069213/razor-why-is-my-variable-not-in-scope

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!