【问题标题】:Razor: Why is my variable not in scope剃刀:为什么我的变量不在范围内
【发布时间】:2011-05-20 08:15:44
【问题描述】:
@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。有没有办法解决这个问题?

【问题讨论】:

    标签: c# razor


    【解决方案1】:

    @functions 部分中定义变量。

    普通的@{ 将您的代码放在某个方法体中。使用@functions 定义类成员。

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

    关于这个问题的更多阅读:SLaks Dissecting razor 系列。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 不不不不。这是一个可怕的想法!如果两个人同时点击您的页面,则该值将被覆盖 - 而且它只会闲置而不会被垃圾收集(问题较小)。
      猜你喜欢
      • 2023-04-02
      • 1970-01-01
      • 2017-10-25
      • 1970-01-01
      • 1970-01-01
      • 2016-04-08
      • 1970-01-01
      • 2016-05-26
      • 1970-01-01
      相关资源
      最近更新 更多