我有一个mvc剃刀视图,其模型填充如下:

public class HomeController : Controller
    {

        private IDataSource _db;

        public HomeController (IDataSource db)
        {
            _db = db;
        }


        public ActionResult Events()
        {
            var allevents = _db.Events;
            ViewBag.Title = "Events";
            return View(allevents);
        }


    }


事件模型如下所示:

 public class Event
    {
        public virtual int Id { get; set; }
        public virtual string Title { get; set; }
        public virtual string Description { get; set; }
        public virtual Location Location {get;set;}
        public virtual DateTime StartDate {get;set;}
        public virtual DateTime EndDate { get; set; }
    }


我想在我的视图中显示项目,以便按月份名称分组。例如:

十月

EventA标题,EventA描述等

EventB标题,EventA说明等

十一月

EventC标题,EventC描述等

如果可能的话,您可以进一步按年份细分,然后按月发布,但这并不是完全必要的,因为我看不到会提前一年输入事件的情况。

我已经在剃刀视图中尝试过此方法,但似乎略有偏离...

@{var monthList = from e in Model
group e by e.StartDate.Month into g
orderby g.Key
select g;

foreach(var monthGroup in monthList)
{

    string month = monthGroup.Key.ToString();
<h2 class="h4 pi-weight-700 pi-uppercase pi-has-bg pi-margin-bottom-25">
    @month
</h2>
    foreach (Model e in monthGroup)
    {
        // do something with the events
    }
}}

最佳答案

假设开始日期和结束日期在同一个月,我将执行以下操作(在控制器中):

var groupedEvents = _db.Events.ToList().GroupBy(k => new DateTime(k.StartDate.Year, k.StartDate.Month, 1)).OrderBy(k => k.Key).ToDictionary(k => k.Key, v => v.ToList());
return View(groupedEvents);


然后在视图中浏览字典。您可以通过以下方式获取月份名称:

@model IDictionary<DateTime, List<Event>>
@foreach(var item in Model)
{
     //Display month name
     <h1>@item.Key.ToString("MMM", CultureInfo.InvariantCulture);</h1>
     foreach(var ev in item.Value)
     {
         //Row specific code
     }
}

09-25 16:52