C# 在重定向之前设置 Viewbag
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14497711/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set Viewbag before Redirect
提问by daniel
Is it possible to set the ViewBag
before I call a redirection?
是否可以ViewBag
在调用重定向之前设置?
I want something like:
我想要这样的东西:
@ViewBag.Message="MyMessage";
RedirectToAction("MyAction");
采纳答案by Rapha?l Althaus
When you use redirection, you shall not use ViewBag
, but TempData
使用重定向时,不应使用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();
}
回答by Jon P
Or you can use Session for alternative:
或者您可以使用 Session 替代:
Session["message"] = "MyMessage";
RedirectToAction("MyAction");
and then call it whenever you need.
然后在需要时调用它。
UPDATE
更新
Also, as what @James said in his comment, it would be safe to nullify or clear the value of that specific session after you use it in order to avoid unwanted junk data or outdated value.
此外,正如@James 在他的评论中所说的那样,在使用该特定会话后取消或清除它的值是安全的,以避免不需要的垃圾数据或过时的值。
回答by laszlokiss88
回答by RAVI VAGHELA
I did like this..and its working for me... here I'm changing password and on success I want to set success message to viewbag to display on view..
我确实喜欢这个......它对我有用......在这里我正在更改密码,成功后我想将成功消息设置为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);
}
回答by Paul Zahra
Summary
The ViewData and ViewBag objects give you ways to access those extra pieces of data that go alongside your model, however for more complex data, you can move up to the ViewModel. TempData, on the other hand, is geared specifically for working with data on HTTP redirects, so remember to be cautious when using TempData.
概括
ViewData 和 ViewBag 对象为您提供了访问模型旁边的那些额外数据的方法,但是对于更复杂的数据,您可以向上移动到 ViewModel。另一方面,TempData 专门用于处理 HTTP 重定向上的数据,因此请记住在使用 TempData 时要小心。