剃刀:为什么我的变量不在范围内
@inherits umbraco.MacroEngines.DynamicNodeContext @using System.Collections; @{ List qa = new List(); } //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可以在递归帮助器中访问。 有没有解决的办法?
在@functions
部分中定义变量。
正常@{
将您的代码放在某个方法体中。 使用@functions
定义类成员。
@functions{ List qa = new List (); }
更多关于此事的解读: SLaks解剖剃刀系列。
在Razor 3.2.3中,似乎在@functions
声明的变量需要声明为static
。 似乎很不幸。 如果有其他方法,请纠正我。
@functions { static List qa = new List (); } @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) } }