0

我在控制器中有以下代码:

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();

}

这是视图中的代码:

@Html.ActionLink("Previous Week's Songs", "Index", new { date = "PreviousDate" }) <br />
@Html.ActionLink("Next Week's Songs", "Index", new { date = "NextDate" })

如果用户单击 PreviousDate,它将被发送回控制器并选择上一个日期。第一次它工作正常。问题第二次出现。由于 latestDate 再次计算,但它基本上应该使用 PreviousDate 作为 latestDate 而不是再次计算 latestDate。有没有办法坚持 PreviousDate?还是从视图传回?

这是一个示例:如果 latestDate 是 08/27/2012 第一次加载,当我按 previousDate 时它会加载日期 08/25/2012 但是当我再次按 PreviousDate 而不是使用 08/25/2012 作为 latestDate 它再次使用 08 /27/2012 为最新日期。

TopDate 类:

public class Top10Date
    {
        [Key]
        public int DateId { get; set; }
        public DateTime Date { get; set; }        
    }
4

2 回答 2

2

你可能想做:

return View(latestDate);

所以模型活页夹把它捡起来

于 2012-08-27T23:49:04.117 回答
2

您需要将显示的当前日期以及 PreviousDate 和 NextDate 的“子操作”传递回控制器。

在控制器中:

    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();
    }

进而

@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 })
于 2012-08-28T00:03:42.963 回答