Should I be passing values through RedirectToAction or TempData?

后端 未结 2 1668
说谎
说谎 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:58

    It sounds like you are coupling your action methods to your end result too tightly.

    I would refactor a little bit; you would have your Index Method like so:

     public ActionResult Index()
     {
          HTMLMVCCalendar.Models.MonthModel someModel = new HTMLMVCCalendar.Models.MonthModel();
    
          someModel.DateTime = DateTime.Now; // whatever
    
          return View(someModel);
     }
    

    Then, when you need to recalculate your calendar, you simply post to the same URL which returns the same view with new view model data.

     [HttpPost]
     public ActionResult Index(HTMLMVCCalendar.Models.MonthModel previousModel, bool? goForward)
     {
          if(goForward.HasValue && goForward.Value)
                previousModel.DateTime = previousModel.DateTime.AddMonths(1);
          else
                previousModel.DateTime = previousModel.DateTime.AddMonths(-1);
    
          return View(previousModel);
     }
    

    You stay on the same URL and present the same view, but with the changes that you need. You dont need a specific endpoint for each action.

提交回复
热议问题