我看过一些文章(甚至是 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/