【发布时间】:2013-01-07 23:52:14
【问题描述】:
是否可以在我调用重定向之前设置ViewBag?
我想要类似的东西:
@ViewBag.Message="MyMessage";
RedirectToAction("MyAction");
【问题讨论】:
标签: c# asp.net-mvc
是否可以在我调用重定向之前设置ViewBag?
我想要类似的东西:
@ViewBag.Message="MyMessage";
RedirectToAction("MyAction");
【问题讨论】:
标签: c# asp.net-mvc
使用重定向时,不能使用ViewBag,而应使用TempData
public ActionResult Action1 () {
TempData["shortMessage"] = "MyMessage";
return RedirectToAction("Action2");
}
public ActionResult Action2 () {
//now I can populate my ViewBag (if I want to) with the TempData["shortMessage"] content
ViewBag.Message = TempData["shortMessage"].ToString();
return View();
}
【讨论】:
您可以在这种情况下使用 TempData。 Here 是对 ViewBag、ViewData 和 TempData 的一些解释。
【讨论】:
我确实喜欢这个……它对我有用…… 在这里我正在更改密码,成功后我想将成功消息设置到 viewbag 以显示在视图中..
public ActionResult ChangePass()
{
ChangePassword CP = new ChangePassword();
if (TempData["status"] != null)
{
ViewBag.Status = "Success";
TempData.Remove("status");
}
return View(CP);
}
[HttpPost]
public ActionResult ChangePass(ChangePassword obj)
{
if (ModelState.IsValid)
{
int pid = Session.GetDataFromSession<int>("ssnPersonnelID");
PersonnelMaster PM = db.PersonnelMasters.SingleOrDefault(x => x.PersonnelID == pid);
PM.Password = obj.NewPassword;
PM.Mdate = DateTime.Now;
db.SaveChanges();
TempData["status"] = "Success";
return RedirectToAction("ChangePass");
}
return View(obj);
}
【讨论】:
总结
ViewData 和 ViewBag 对象为您提供了访问模型旁边的额外数据的方法,但是对于更复杂的数据,您可以向上移动到 ViewModel。另一方面,TempData 专门用于处理 HTTP 重定向上的数据,因此请记住在使用 TempData 时要小心。
【讨论】:
或者您可以使用 Session 替代:
Session["message"] = "MyMessage";
RedirectToAction("MyAction");
然后在需要时调用它。
更新
此外,正如@James 在他的评论中所说,在您使用该特定会话后,可以安全地取消或清除它的值,以避免不需要的垃圾数据或过时的值。
【讨论】: