我有一个模型,其中包含事件的列表,其中包括开始日期,结束日期,开始时间,结束时间,标题和描述。我需要根据开始日期对它们进行分组,然后根据开始时间进行分组并在我的局部视图中显示,如所附的图像。
这是我的模特:
public int eventID { get; set; }
[DisplayName("Title")]
public string eventTitle { get; set; }
[DisplayName("Description")]
public string PaperDescription { get; set; }
[DisplayName("Location")]
public string ClassLocation { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
public DateTime? StartDate { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
public DateTime? EndDate { get; set; }
[DataType(DataType.Time)]
public TimeSpan? StartTime { get; set; }
[DataType(DataType.Time)]
public TimeSpan? EndTime { get; set; }
这是我的控制器:
public PartialViewResult _Events(DateTime? date)
{
var eventList = db.Classes_tbl.Where(x => x.StartDate == date).OrderBy(x => x.StartDate).ToList();
return PartialView(eventList);
}
这是我的部分:
@foreach (var eventClass in Model.classesViewModel)
{
if (eventClass.classType == ClassType.Event)
{
@eventClass.StartTime.GetValueOrDefault().Hours<br />
@eventClass.EndTime<br />
@eventClass.ClassTitle<br />
}
}
有人可以帮我吗?我对MVC非常陌生,无法弄清楚该怎么做。非常感谢!
答案 0 :(得分:0)
创建新的ViewModel EventGroup
然后选择您的事件并按开始日期对事件进行分组,然后将此视图模型传递给您的视图
var eventList = events
.GroupBy(x => x.StartDate).Select(g => new EventGroup
{
StartDate = g.Key,
Events = g.OrderBy(x => x.StartTime).ToList()
}).ToList();
public class EventGroup
{
public List<Event> Events { get; set; }
public DateTime? StartDate { get; set; }
}
public class Event
{
public int eventID { get; set; }
[DisplayName("Title")]
public string eventTitle { get; set; }
[DisplayName("Description")]
public string PaperDescription { get; set; }
[DisplayName("Location")]
public string ClassLocation { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
public DateTime? StartDate { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
public DateTime? EndDate { get; set; }
[DataType(DataType.Time)]
public TimeSpan? StartTime { get; set; }
[DataType(DataType.Time)]
public TimeSpan? EndTime { get; set; }
}
<div>
@foreach (var EventGroup in Model.EventGroups)
{
@EventGroup.StartDate
@foreach (var Event in EventGroup.Events)
{
if (Event.classType == Event.Event)
{
@Event.StartTime.GetValueOrDefault().Hours<br />
@Event.EndTime<br />
@Event.ClassTitle<br />
}
}
}
</div>