c#-使用剃刀在表中按日期对模型元素进行分组

我试图基于日期时间值从模型生成多个表.这是我到目前为止的内容:

@{
    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...

解决方法:

通过使代码更简洁,可以更好地编写代码.

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

  }
  </table>
}

如果您不关心可读性,则可以始终使用@ Html.Raw(“< / table>”).

上一篇:剑道DatePicker最大值和最小值不限制文本输入


下一篇:C#-ASP.NET MVC4代码优先-数据验证不起作用