Reputation: 3256
I have following code in controller:
public ActionResult Index(string date)
{
var topsong = db.TopSongs;
var topDate = db.TopDates;
var latestDate = topDate.OrderByDescending(d => d.Date).FirstOrDefault();
if (date == "PreviousDate")
{
latestDate = topDate.Where(d => d.Date < latestDate.Date).OrderByDescending(d => d.Date).FirstOrDefault();
}
if (date == "NextDate")
{
latestDate = topDate.Where(d => d.Date > latestDate.Date).OrderBy(d => d.Date).FirstOrDefault();
}
....
return View();
}
Here is code in View:
@Html.ActionLink("Previous Week's Songs", "Index", new { date = "PreviousDate" }) <br />
@Html.ActionLink("Next Week's Songs", "Index", new { date = "NextDate" })
If user click on PreviousDate it is sent back to controller and it chooses the previous date. First time it works fine. Problem comes the second time. As latestDate is calculated again but it should basically use PreviousDate as latestDate not calculate latestDate again. Is there a way to persist PreviousDate? Or pass it back from the View?
Here is an example: If latestDate is 08/27/2012 first time it is loaded when i press previousDate it loads date 08/25/2012 but when i press PreviousDate again instead of using 08/25/2012 as latestDate it again uses 08/27/2012 as latest date.
TopDate class:
public class Top10Date
{
[Key]
public int DateId { get; set; }
public DateTime Date { get; set; }
}
Upvotes: 0
Views: 195
Reputation: 1621
You will want to pass the current date that is being shown as well as the "sub-action" of PreviousDate and NextDate back to the controller.
In the controller:
public ActionResult Index(string date, DateTime? latestDate)
{
var topsong = db.TopSongs;
var topDate = db.TopDates;
if (!latestDate.HasValue)
latestDate = (DateTime?)(topDate.OrderByDescending(d => d.Date).FirstOrDefault());
if (date.Value == "PreviousDate")
{
latestDate = (DateTime?)(topDate.Where(d => d.Date < latestDate.Date).OrderByDescending(d => d.Date).FirstOrDefault());
}
if (date.Value == "NextDate")
{
latestDate = (DateTime?)(topDate.Where(d => d.Date > latestDate.Date).OrderBy(d => d.Date).FirstOrDefault());
}
....
ViewBag.latestDate = latestDate
return View();
}
And then
@Html.ActionLink("Previous Week's Songs", "Index", new { date = "PreviousDate", ViewBag.latestDate }) <br />
@Html.ActionLink("Next Week's Songs", "Index", new { date = "NextDate", ViewBag.latestDate })
Upvotes: 2
Reputation: 31610
You probably want to do:
return View(latestDate);
So the model binder picks it up
Upvotes: 2