2011-05-20 58 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

相關問題