0

I want to make a simple Blog Post Archive List like below

2014

  • January (1)

2013

  • December (1)
  • November (14) -> Link to search with date
  • October (3)
  • May (5)
  • April (3)

I need to send this via ViewBag.Archives. When I perform below SQL in SQL Server Management Studio.

select year(Created) as PostYear, datename(month,Created) as PostMonth,count(ID) as ArticleAmount from Post group by year(Created), datename(MONTH,Created) order by PostYear, PostMonth

I get:

PostYear    PostMonth   ArticleAmount
2010        February    1
2011        September   1
2012        April       1
2012        February    1
2013        February    4
2013        March       1
2014        February    1

My Code:

ViewBag.Archives = db.Posts
.GroupBy(group => new { group.Created.Year, group.Created.Month })
.Select(x => new { count = x.Count(), Year = x.Key.Year, Month = x.Key.Month });

My View:

@foreach (var item in ViewBag.Archives)
{
    <p>@item.Year</p>
}

ERROR: Additional information: 'object' does not contain a definition for 'Year'

Thank you

Brad Larson
  • 170,088
  • 45
  • 397
  • 571
Sacmalama
  • 21
  • 5

1 Answers1

0

Are you looking for something like:

ViewBag.Archives = db.Posts
            .GroupBy(group => new {group.Created.Year, group.Created.Month})
            .Take(5)
            .Select(x => new GuestBookPost()
            {
                count = x.Count,
                Year = x.Key.Created.Year,
                Month = x.Key.Created.Month
            }).ToList();

EDIT

  • Use the ToList() on the select :).
  • Try using an object or a model to store the data in, this will also make is easier to add month names as accessing in the view. Example below, replaced "ObjectName()", with "PostGroup":

public class GuestbookPost {
public int Count { get; set; }
public int Year { get; set; }
public int Month { get; set; }
}

PS: Sorry for the bad formatting, still learning :)

Jelle Oosterbosch
  • 1,731
  • 15
  • 17