4

在我看来,Razor 告诉我我的 Foreach 循环缺少一个结束大括号 ( }) 它还告诉我我<div class="row">的结束标记丢失了。

 @{int spanCounter = 0;}
 @foreach (var item in Model)
 {
     if(spanCounter == 0)
     {
        <div class="row">
     }
     spanCounter += item.Span;

     <div class="span@(item.Span)">
       @item.Html
     </div>

     @if(spanCounter == 12)
     {
       @spanCounter = 0

       </div>
     }    
 }

我见过类似的问题,但他们似乎专注于 Razor 期望正确分层的事实。即,这是非法的:

if(condition)
{
    <foo>
}
else
{
    <foo>
}
</foo>

更新 模型是 Html 内容“块”的列表

为了更清楚一点,我想在“行”中写出多个块(<div></div><div></div>

  1. 如果 spanCounter 为 0 BEGIN 行。
  2. 写入内容:<div></div>阻塞直到达到最大跨度宽度 (12)
  3. 结束行,重置计数器,返回 1。
4

4 回答 4

4

还有另一种避免重复代码的解决方法:

if(condition)
{
    @:<foo>
}
else
{
    @:<foo>
}
</foo>
于 2013-12-15T10:32:51.520 回答
2

换成这样

@{int spanCounter = 0;}
@foreach (var item in Model)
{
  if (spanCounter == 0 || spanCounter == 12)
  {
  <div class="row">
  @spanCounter += @item.Span;
  <div class="span@(item.Span)">
      @item.Html
  </div>
  </div>
  }
  else
  {
    spanCounter += item.Span;
  <div class="span(@item.Span)">
  @item.Html
  </div>
  }
}
于 2012-09-03T08:32:44.683 回答
1

这本身并不能解决您的代码,但它与 Razor 与右括号的混淆有关,所以我把它放在这里,以防有人真的像我一样难过。在 VS 2012 中,Razor 感到困惑,我终于在评论中缩小了一个撇号,就像这样。注意右大括号不是黄色的:

在此处输入图像描述

但是,如果您在评论中省略撇号,它可以正常工作:

在此处输入图像描述

于 2016-03-09T01:51:38.003 回答
0

The reason you were getting this error is that the closing tag was being conditionally rendered, therefore you could not guarantee that it would be added to the view:

The spanCounter variable is being incremented here:

    spanCounter += item.Span;

    <div class="span@(item.Span)">
       @item.Html
    </div>

therefore, you cannot guarantee that it will meet the condition of this if statement i.e. it might be greater that 12 by this point:

    @if(spanCounter == 12)
    {
       </div>
    }    

You need to provide full mark up for elements that are being conditionally rendered. You need something like:

var spanCounter = 0;
<div class="row">

@foreach (var item in Model)
{
    spanCounter += item.Span;
    <div class="span@(item.Span)">
        @item.Html
    </div>
   if(spanCounter == 12)
   {
       spanCounter = 0;
   }
}

</div>
于 2012-09-03T08:41:23.163 回答