Group Model elements by Date in Table using Razor

asp.net-mvc, c#, html-table, ienumerable, razor

Solution

You can write it better by making your code a little bit cleaner.

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

  }
  </table>
}

If you are not concerned about the readability, you can always use `@Html.Raw("</table>")`.

Problem

I'm trying to generate multiple tables from a model based on a datetime value. This is what I have so far: ``` @{ 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> } } } ``` The problem I am having is that I can't type closing table html tags (at least, in Visual Studio 2013), without the opening tags first. I've tried having: ``` if(first) { //Create the first part. } else { </tbody> </table> // Create the first part here instead. } ``` But not only does this break the DRY principle, but it doesn't work for the same reason mentioned above. I had thought that this would have been a simple enough task. Either I'm missing something, or I've had some oversights. Either way, any help would be greatly appreciated. If anything here isn't clear, please let me know and I'll happily clarify. This is the expected result, for clarity: ``` 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... ```

Original source