Should I be passing values through RedirectToAction or TempData?

后端 未结 2 1555
说谎
说谎 2021-01-20 06:12

I\'ve seen some articles (even MSDN) suggest TempData for passing data between ActionMethods. But I\'ve seen others here say that TempData should be avoided. What\'s the bes

2条回答
  •  有刺的猬
    2021-01-20 06:57

    I came up with this. Is this bad, good, should be improved upon?

    RAZOR/HTML:

    @using (Html.BeginForm("Previous", "Home", new{ year = @year, month = @month }, FormMethod.Post)) { }         @using (Html.BeginForm("Next", "Home", new { year = @year, month = @month }, FormMethod.Post)) { }

    Controller/Action Methods:

    public ActionResult Index(int? year = 2012 , int? month = 2)
            {
                ViewBag.Message = "Welcome to ASP.NET MVC!";
    
                Calendar monthEventsCal = new Calendar();
    
                HTMLMVCCalendar.Models.MonthModel allMonthEvents = monthEventsCal.monthEvents(year.Value, month.Value);
                return View("Index", allMonthEvents);
            }
    
            [HttpPost]
            public ActionResult Previous(int? year = 2012, int? month = 2)
            {
                Calendar monthEventsCal = new Calendar();
    
                var newMonth = monthEventsCal.previousMonth(year.Value, month.Value);
    
                int currMonth = newMonth.Item2;
                int currYear = newMonth.Item1;
    
                return RedirectToAction("Index", "Home", new { month = currMonth, year = currYear });
            }
    
            [HttpPost]
            public ActionResult Next(int? year = 2012, int? month = 2)
            {
                Calendar monthEventsCal = new Calendar();
    
                var newMonth = monthEventsCal.nextMonth(year.Value, month.Value);
    
                int currMonth = newMonth.Item2;
                int currYear = newMonth.Item1;
    
                return RedirectToAction("Index", "Home", new { month = currMonth, year = currYear });
            }
    

    Global.asax.cs:

    public static void RegisterRoutes(RouteCollection routes)
            {
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
                routes.MapRoute(
                    "Default", // Route name
                    "{controller}/{action}/{month}/{year}", // URL with parameters
                    new { controller = "Home", action = "Index", month = UrlParameter.Optional, year = UrlParameter.Optional } // Parameter defaults
                    //"{controller}/{action}/{id}", // URL with parameters
                    //new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
                );
    
            }
    

提交回复
热议问题