【问题标题】:What would be the correct Razor syntax that contains conditional logic包含条件逻辑的正确 Razor 语法是什么
【发布时间】:2014-12-18 20:27:24
【问题描述】:

我想在 razor 文件中每行显示 3 个项目。我必须在每 3 个项目处添加 div class="row" 和结束标记。以下是我的最佳尝试:

@{

  int maxInRow = 3;
  int counter = 1;

  <div class="main">

  @foreach(var item in allItems)
  {

    if(counter == 1)
    {
        <div class="row">
    }

    <div class="article">Here is the article.</div>

    @{counter++;}
    if(counter == maxInRow)
    {
        counter = 1;
        </div>
    }

  </div>
}

正确的 Razor 语法是什么?

【问题讨论】:

  • 您是否遇到任何错误?

标签: c# razor


【解决方案1】:

您可以使用 LINQ 和分组使这变得非常简单

var itemsInGroupsOf3 = allItems.Select((item, i) => new { Index = i, Item = item })
                               .GroupBy(i => i.Index / 3);

foreach(var group in itemsInGroupsOf3)
{
    var groupItems = group.Select(g => g.Item);

    <div class="row">
        @foreach(var item in groupItems)
        {
            <div class="article">Here is the article.</div>
        }
    </div>
}

【讨论】:

  • 比条件 HTML 更好的方法(容易出错且难以维护)。
【解决方案2】:

我认为你可以使用下面的代码来实现:

@{
   <div class="main">
       @for (int i = 0; i < allItems.Count; i += 3)
       {
          <div class="row">
              @for (int j = i; j < i + 3 && j < allItems.Count; j++)
              {
                <div class="article">Here is the article. @allItems[j]</div>
              }
          </div>
        }
   </div>            
  }

如果不起作用,请发表评论。

【讨论】:

  • 我需要 i 和 J 作为计数器,所以我选择了这个作为答案。
猜你喜欢
  • 2015-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-23
  • 2017-03-28
  • 1970-01-01
相关资源
最近更新 更多