c# - 我应该通过 RedirectToAction 还是 TempData 传递值?

标签 c# asp.net-mvc asp.net-mvc-3 redirecttoaction tempdata

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

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

注2:This is related, but not the same.

查看:

<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>

Controller 方法:

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

最佳答案

听起来您将操作方法​​与最终结果紧密结合在一起。

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

 public ActionResult Index()
 {
      HTMLMVCCalendar.Models.MonthModel someModel = new HTMLMVCCalendar.Models.MonthModel();

      someModel.DateTime = DateTime.Now; // whatever

      return View(someModel);
 }

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

 [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 上并呈现相同的 View ,但进行了您需要的更改。您不需要为每个操作指定一个特定的端点。

关于c# - 我应该通过 RedirectToAction 还是 TempData 传递值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10193709/

相关文章:

c# - 如何通过对话框选择文件夹并处理其中包含的所有文件

c# - 将路径转换为其 GUID 形式

c# - 将方法从 View 移动到 View 模型 - WPF MVVM

c# - 单元测试角色访问方法

c# - ASP.NET MVC 中具有多个 View 的 Telerik 样式

c# - 为什么 object.ToString() 没有反函数?

c# - 我怎么能知道它是成功的还是被拒绝的平衡支付交易

asp.net-mvc - 将 Entity Framework 数据模型放在 MVC 应用程序中的何处?具体例子

asp.net-mvc - MVC3 如何禁用/启用 ActionLink

asp.net-mvc-3 - 当两个网格位于同一页面上时进行排序