我有几年作为按钮。像
2018 2017 2016 2015
我正在使用for
循环来获取年份作为按钮。
@model List<MyRecord.Models.RecordList>
var year = DateTime.Now.Year;
for (var i = year; i > 2012; i--)
{
var j = @i - 1;
<div class="col-md-1 ">
@Html.ActionLink(i.ToString(), "MyPage", new { i = i })
</div>
}
<h3>@ModelYear.Year</h3>
@foreach (var groupMonth in Model.Records.GroupBy(recordLists => new { recordLists.date.Value.Year, recordLists.date.Value.Month }))
{
<h3 class="monthHeader"> @System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(groupMonth.Key.Month)</h3>
foreach (var recordLists in groupMonth)
{
<div class="row">
@Html.Partial("_PartialView", recordList)
</div>
}
}
public ActionResult Archives(int i = 0)
{
var recordLists = new List<RecordList>();
if(i == 0)
recordLists = _db.recordlists
.Where(p => p.date.Value.Year == DateTime.Now.Year)
.OrderByDescending(p => p.date)
.ToList();
else
recordLists = _db.recordlists
.Where(p => p.date.Value.Year == i)
.OrderByDescending(p => p.date)
.ToList();
return View(new ModelYear{Records = recordLists, Year = i});
}
型号:
命名空间MyRecord.Models
{
using System;
using System.Collections.Generic;
公共局部类RecordList {
public int id { get; set; }
public string title { get; set; }
public Nullable<System.DateTime> date { get; set; }
}
public class ModelYear
{
public int Year { get; set; }
public List<RecordList> Records { get; set; }
}
}
当我单击任何年份时,将显示基于月份的该年的记录。我能够得到月份名称,而不是年份。我的问题是我需要将所选的年份显示为标签或标题。如果我单击2016,则应该看到类似以下内容的
:**2016**
Jan
record 1
record 2
如何显示点击年份?
答案 0 :(得分:1)
为什么不将其包含在Model类中?
public class Model
{
public int Year {get;set;}
public List<RecordList> Records {get;set;}
}
然后您可以在控制器中进行设置:
public ActionResult Archives(int i = 0)
{
var recordLists = new List<RecordList>();
if(i == 0)
recordLists = _db.recordlists.Where(p => p.date.Value.Year == DateTime.Now.Year)
.OrderByDescending(p => p.date).ToList();
else{
recordLists = _db.recordlists.Where(p => p.date.Value.Year == i).OrderByDescending(p => p.date).ToList();
}
return View(new Model{Records = recordLists, Year = i});
}
并在视图中显示它:
<h1>@Model.Year</h1>
@foreach (var groupMonth in Model.Records.GroupBy(recordLists => new { recordLists.date.Value.Year, recordLists.date.Value.Month }))
{
<h3 class="monthHeader"> @System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(groupMonth.Key.Month)</h3>
foreach (var recordLists in groupMonth)
{
<div class="row">
@Html.Partial("_PartialView", recordList)
</div>
}
}