如何在Controller MVC3中保持值

时间:2012-08-27 23:46:00

标签: c# asp.net-mvc-3

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

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

}

以下是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?或者从View中传回来?

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

TopDate类:

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

2 个答案:

答案 0 :(得分:2)

您可能想要这样做:

return View(latestDate);

所以模型绑定器选择它

答案 1 :(得分: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 })