0

这是我的行动

[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);
        }
4

1 回答 1

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)
}
于 2013-05-02T14:11:35.127 回答