我有以下代码HomeController
;它获取最新日期并根据该日期显示歌曲。
public ActionResult Index()
{
var topsong = db.TopSongs;
var topDate = db.TopDates;
var latestDate = topDate.OrderByDescending(d => d.Date).FirstOrDefault();
int dateId = topDate.OrderByDescending(d => d.DateId).FirstOrDefault().DateId;
var topTitles = topsong.Where(s => s.DateId == latestDate.DateId).ToList();
ViewBag.Message = "Top Songs";
ViewBag.latestDate = latestDate.Date.ToShortDateString();
return View(topTitles);
}
这会进入数据库并选择最新日期——比如 08/25/2012——并显示与该日期对应的所有歌曲。这部分工作正常;现在我想添加一个功能,用户可以从数据库中选择以前的日期或下一个日期,并据此显示歌曲。
我想要做的是在视图中添加上一个和下一个日期按钮。像这样:
<h2>Songs Updated On: @ViewBag.latestDate</h2>
@Html.ActionLink("Previous Week's Songs", "Index", new { });
@Html.ActionLink("Next Week's Songs", "Index", new { });
由于我是 MVC3 的新手,有人可以告诉我如何让上一个和下一个日期出现吗?如果我在视图中计算它们,我如何将它们传递回控制器以显示这些日期的歌曲?
这是示例日期表: DateId Date 1 08/25/2012 2 08/20/2012 3 09/21/2012
更新代码:
这是 HomeController 的代码:
public ActionResult Index(DateTime? date = null)
{
var topsong = db.TopSongs;
var topDate = db.TopDates;
var latestDate = (date.HasValue) ? date.Value : topDate.OrderByDescending(d => d.Date).FirstOrDefault();
//var latestDate = topDate.OrderByDescending(d => d.Date).FirstOrDefault();
int dateId = topDate.OrderByDescending(d => d.DateId).FirstOrDefault().DateId;
var topTitles = topsong.Where(s => s.DateId == latestDate.DateId).ToList();
/////
ViewBag.NextDate = topDate.Where(d => d.Date > latestDate).OrderBy(d => d.Date).FirstOrDefault();
ViewBag.PreviousDate = topDate.Where(d => d.Date < latestDate).OrderByDescending(d => d.Date).FirstOrDefault();
////////
ViewBag.Dates = topDate.Select(d => d.Date).Distinct();
ViewBag.latestDate = latestDate.Date.ToShortDateString();
return View(topTitles);
}
Index.cshtml 的代码
@model IEnumerable<App.Models.TopSong>
@{
ViewBag.Title = "Top Songs";
var songs = ViewBag.songs;
}
<h1>@ViewBag.Message</h1>
<h2>Song's Updated On: @ViewBag.latestDate</h2>
@Html.ActionLink("Previous Week's Songs", "Index", new { date=@ViewBag.PreviousDate });
@Html.ActionLink("Next Week's Songs", "Index", new { date=@ViewBag.NextDate });
基本上我只是希望能够使用操作链接转到上一个或下一个日期。我尝试了上面的代码,但它不起作用。