我的视图有get和post方法,在get方法中我设置了几个ViewData对象的值。但是当我调用post方法时,这些ViewData对象变为null。我需要在post方法中重置它们吗?这是我的代码:
public ActionResult Index()
{
ViewData["afceaststandings"] = GetStandingsForGrid("2017", "AFC East");
ViewData["afccentralstandings"] = GetStandingsForGrid("2017", "AFC Central");
ViewData["afcweststandings"] = GetStandingsForGrid("2017", "AFC West");
return View("Index");
}
[HttpPost]
public ActionResult Index(QBRating qbm)
{
if (ModelState.IsValid)
{
string Result;
double dblResult;
qbm.Completion = ((qbm.Completion - 30) * 0.05);
if (qbm.Completion < 0)
{
qbm.Completion = 0;
}
if (qbm.Completion > 2.375)
{
qbm.Completion = 2.375;
}
qbm.Gain = ((qbm.Gain - 3) * 0.25);
if (qbm.Gain < 0)
{
qbm.Gain = 0;
}
if (qbm.Gain > 2.375)
{
qbm.Gain = 2.375;
}
qbm.Touchdown = (qbm.Touchdown * 0.2);
if (qbm.Touchdown > 2.375)
{
qbm.Touchdown = 2.375;
}
qbm.Interception = (2.375 - (qbm.Interception * 0.25));
if (qbm.Interception < 0)
{
qbm.Interception = 0;
}
dblResult = Math.Round((((qbm.Completion + qbm.Gain + qbm.Touchdown + qbm.Interception) / 6) * 100), 2);
Result = "QB Rating = " + Convert.ToString(dblResult);
TempData["QBRating"] = Result;
}
//invalid - redisplay form with errors
return View(qbm);
}
答案 0 :(得分:1)
是的,需要在POST控制器操作中将值重新分配给ViewData
,因为ViewData
不会在请求之间保留。
你可以使用TempData
来保存请求的数据(它会一直存在于ViewData中,直到下次访问);默认ITempDataProvider
(SessionStateTempDataProvider
)使用SessionState,因此,根据您使用的会话存储类型,您放入TempData的项目可能需要序列化。
答案 1 :(得分:0)
是。 ViewData对象仅在一个请求的生命周期内存在。因此,每个请求必须重新设置您需要的任何变量。