这是我的行动
[ChildActionOnly]
public PartialViewResult ArchiveSidebar()
{
var currentDate = DateTime.Now;
var list = new List<string>();
for (var startDate = new DateTime(2013, 5, 1); startDate.Month <= currentDate.Month; startDate = startDate.AddMonths(1))
{
list.Add(startDate.ToString("MMMM, yyyy"));
if (startDate.Month == currentDate.Month)
break;
}
return PartialView("_ArchiveSidebar", list);
}
这是_ArchiveSidebar
@model List<string>
<div class="sidebar">
<h3>Archive</h3>
@foreach (string archive in Model)
{
<ul>
<li>
<h3>{
@Html.ActionLink(archive, "Archive", "Blog",new{month=archive?,year=archive ?},null)
}
</h3>
</li>
</ul>
}
</div>
在上面的视图中我想得到List的元素来调用带有年份和月份参数的存档操作,我怎样才能获得年份和月份???(我已经放置了哪些?)
这是存档操作
public ActionResult Archive(int month, int year)
{
var posts = _blogRepository.GetPostByDate(year, month);
return View(posts);
}
答案 0 :(得分:0)
首先,创建一个包含月份和年份的视图模型
public class BlogPeriod {
public int Month {get;set;}
public int Year {get;set;}
// if you want to pass the formatted date to your view
// then add this
public string FormattedDate {get;set;}
}
然后使用它来构建列表并将其返回到您的视图
var list = new List<BlogPeriod>();
for (...)
{
// rest of your code goes here
list.Add(new BlogPeriod {
Month = startDate.Month,
Year = startDate.Year,
// do you want your formatted date, add this
FormattedDate = startDate.ToString("MMMM, yyyy")
});
}
return PartialView("_ArchiveSidebar", list);
然后将您的观点更改为
@model IEnumerable<BlogPeriod>
@foreach (string archive in Model)
{
// your markup goes here
@Html.ActionLink(archive, "Archive", "Blog",
new{month=archive.Month, year=archive.Year},null)
}