使用Razor按表中的日期对模型元素进行分组

时间:2013-12-03 11:19:53

标签: c# asp.net-mvc razor ienumerable html-table

我正在尝试根据日期时间值从模型生成多个表。这就是我到目前为止所做的:

@{
    DateTime prev = new DateTime();
    bool first = true;
    foreach(var item in Model)
    {
        DateTime now = item.StartDate;
        // If the current item is a different date to the last one, start a new table.
        if (prev != now)
        { 
            // But if it's not the first entry, it has to close the previous table first.
            if(!first)
            {
                </tbody>
                </table>
            }

            first = false;

           // New table starts.
           <h2>@now.ToString("D")</h2>
           <table>
               <thead>
                    <tr><th>item1</th><th>item2</th><tr>
               </thead>
               <tbody>
               //With entry of this iteration.
                   <tr> <td>@item.item1</td><td>@item.item2</td><tr>
        }
        else 
        {
            //Otherwise just add another row to the current table
            <tr> <td>@item.item1</td><td>@item.item2</td><tr>
        }
    }
}

我遇到的问题是我不能首先输入关闭表格html标签(至少在Visual Studio 2013中),而不使用开始标签。我试过了:

if(first)
{
    //Create the first part.
}
else
{
    </tbody>
    </table>
    // Create the first part here instead.
} 

但这不仅打破了DRY原则,而且由于上述原因而无效。

我原以为这本来就是一项非常简单的任务。要么我错过了什么,要么我有一些疏忽。无论哪种方式,任何帮助将不胜感激。如果这里有任何不明确的地方,请告诉我,我很乐意澄清。

为清晰起见,这是预期的结果:

Wednesday 25 March, 2013
Item1       Item 2
Infohere    Infoheretoo
Infomore    MoreInfo

Thursday 26 March, 2013
Item1       Item2
OhYeah      MoreInfo!
OhLook!     Yup, MoreINfo!

Friday 27 March, 2013
Item1      Item2
Ithink     YouGet
ThePoint   Here....
So         I'm
gonna      stop...

2 个答案:

答案 0 :(得分:4)

您可以通过使代码更清洁来更好地编写它。

@foreach(var group in Model.GroupBy(x=>x.StartDate))
{
  <table>
  @foreach(var item in group)
  {
     //render rows

  }
  </table>
}

如果您不关心可读性,可以随时使用@Html.Raw("</table>")

答案 1 :(得分:0)

Razor不喜欢丢失或不匹配的HTML标记,即使它们被条件逻辑分开(即,在if / else块之间)。您可以绕过这个,在Razor @之后用额外的冒号写出不匹配的标签,例如:

@:</table>