我应该通过RedirectToAction或TempData传递值

本文关键字:TempData RedirectToAction 我应该 | 更新日期: 2023-09-27 18:31:20

我看过一些文章(甚至MSDN)建议使用TempData在ActionMethods之间传递数据。但我在这里看到其他人说应该避免使用TempData。解决此问题的最佳实践方法是什么?

这里有一些代码来显示我的情况。注意:我100%确定,我做错了。这就是我在这里的原因。:)另外,直到最近我一直在做网络表单。

注意2:这是相关的,但并不相同。

视图:

<div>
    @using (Html.BeginForm("Previous", "Home", new {month = @month}, FormMethod.Post)) 
    {
        <input id="previous" type="submit" value="Previous" />
    }
    // This fails but that's another situation
    @using (Html.BeginForm("Next", "Home", new {month = @month, year = @year}, FormMethod.Post))
    {
        <input id="next" type="submit" value="Next" />
    }
</div>

控制器方法:

[HttpPost]
public ActionResult Previous(HTMLMVCCalendar.Models.MonthModel prevMonth)
{
    Calendar monthEventsCal = new Calendar();
    int month = prevMonth.Month;
    int year = prevMonth.Year;
    var newMonth = monthEventsCal.previousMonth(year, month);
    month = newMonth.Item2;
    year = newMonth.Item1;
    return RedirectToAction("Index", "Home", new { month = month });
}
[HttpPost]
public ActionResult Next(HTMLMVCCalendar.Models.MonthModel nextMonth)
{
    Calendar monthEventsCal = new Calendar();
    int month = nextMonth.Month;
    int year = nextMonth.Year;
    var newMonth = monthEventsCal.nextMonth(year, month);
    month = newMonth.Item2;
    year = newMonth.Item1;
    return RedirectToAction("Index", "Home", new { year = year, month = month });
}

我应该通过RedirectToAction或TempData传递值

听起来你把你的操作方法和最终结果耦合得太紧了。

我会重构一点;你会有这样的索引方法:

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

然后,当您需要重新计算日历时,只需发布到同一 URL,该 URL 返回具有新视图模型数据的相同视图。

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

您保留在同一 URL 上并显示相同的视图,但需要进行更改。不需要每个操作的特定终结点。

我想出了这个。这是坏的,好的,应该改进吗?

RAZOR/HTML:

<div>
        @using (Html.BeginForm("Previous", "Home", new{ year = @year, month = @month },  FormMethod.Post)) 
        {
            <input id="previous" type="submit" value="Previous" />
        }
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        @using (Html.BeginForm("Next", "Home", new { year = @year, month = @month }, FormMethod.Post))
        {
            <input id="next" type="submit" value="Next" />
        }
    </div>

控制器/操作方法:

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