I am new Asp.Net Mvc . I am doing a sample application for Blogging . I tried to create Partial view for Archives for categorizing Post according to date .
Month/Year(count)
Post 1
Post 2
Month/Year(count)
Post 1
Post 2
In Controller
[ChildActionOnly]
public ActionResult Archives()
{
var post = from p in db.Posts
group p by new { Month =p.Date.Month, Year = p.Date.Year } into d
select new { Month = d.Key.Month , Year = d.Key.Year , count = d.Key.Count(), PostList = d};
return PartialView(post);
}
Please help me write View for this Action with this Month, Year , Count and collection of Post .
You may be struggling because you are passing an anonymous type into your View. I would create a ViewModel
to represent your type;
public class Archive
{
public string Month { get; set; }
public string Year { get; set; }
public int Count { get; set; }
public ICollection<Post> Posts { get; set; }
}
and then change your action to use the type;
[ChildActionOnly]
public ActionResult Archives()
{
var post = from p in db.Posts
group p by new { Month =p.Date.Month, Year = p.Date.Year } into d
select new Archive { Month = d.Key.Month , Year = d.Key.Year, Count = d.Key.Count(),
PostList = d };
return PartialView(post);
}
and then you can strongly type your view to the Archive
class;
@model IEnumerable<Archive>
@foreach (Archive archive in Model)
{
<h2>
@archive.Month / @archive.Year
</h2>
}
Let me know if I can be of further assistance.
Matt
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.