2011-05-20 57 views
19
@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")) 

变量qa canot在递归助手中被访问。有没有解决的办法?剃刀:为什么我的变量不在范围内

回答

32

定义@functions部分中的变量。

正常@{将您的代码置于某个方法体中。使用@functions来定义类成员。

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

关于此事的更多阅读:SLaks Dissecting razor系列。

+0

Wow..thanks很多 – Luke101 2011-05-23 18:11:50

-1

在Razor 3.2.3中,似乎@functions中声明的变量需要声明为static。看起来不幸。如果有其他方法,请纠正我。

@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) 
    } 
} 
+0

无无无无无。这是一个可怕的主意!如果两个人同时击中你的页面,价值将被覆盖 - 再加上它会坐在旁边,不会被垃圾收集(更少的问题)。 – 2017-05-23 01:09:11

相关问题