[英]How to pass tempdata in RedirectToAction in ASP.Net MVC
I need to pass one logout successful message in one of the views but I am not able to do so.我需要在其中一个视图中传递一条注销成功消息,但我无法这样做。 Here is what I have.
这就是我所拥有的。
Not Working Solution:不工作解决方案:
//LogController:
public ActionResult Logoff()
{
DoLogOff();
TempData["Message"] = "Success";
return RedirectToAction("Index", "Home");
}
// HomeController
public ActionResult Index()
{
return View();
}
Index CSHTML File:索引 CSHTML 文件:
@Html.Partial("../Home/DisplayPreview")
DisplayPreview CSHTML File:显示预览 CSHTML 文件:
@TempData["Message"]
Working Solution工作解决方案
public ActionResult Logoff()
{
DoLogOff();
return RedirectToAction("Index", "Home", new { message = "Logout Successful!" });
}
public ActionResult Index(string message)
{
if (!string.IsNullOrEmpty(message))
TempData["Message"] = message;
return View();
}
Index CSHTML File:索引 CSHTML 文件:
@TempData["Message"]
But I want something like my first solution.但我想要我的第一个解决方案。
In the controller;在控制器中;
public ActionResult Index()
{
ViewBag.Message = TempData["Message"];
return View();
}
public ActionResult Logoff()
{
DoLogOff();
TempData["Message"] = "Success";
return RedirectToAction("Index", "Home");
}
Then you can use it in view like;然后你可以在视图中使用它;
@ViewBag.Message
See if this works:看看这是否有效:
public ActionResult Logoff()
{
DoLogOff();
ControllerContext.Controller.TempData["Message"] = "Success";
return RedirectToAction("Index", "Home");
}
Since you don't show what DoLogOff() does, my guess is that you are abandoning the session, which means any data stored in session (like TempData) is lost.由于您没有显示 DoLogOff() 的作用,我的猜测是您正在放弃会话,这意味着存储在会话中的任何数据(如 TempData)都将丢失。 A new session does not get generated until the next page refresh, so it doesn't work.
在下一页刷新之前不会生成新会话,因此它不起作用。
What you might try is simply passing a flag to your Index view that will show the logged off message if it's present.您可能尝试的只是将一个标志传递给您的索引视图,如果它存在,它将显示已注销的消息。 I would NOT use the string message, like you show in your "working" example, because this can be coopted by attackers to redirect people to malicious sites.
我不会使用字符串消息,就像您在“工作”示例中显示的那样,因为攻击者可以利用它来将人们重定向到恶意站点。
hi i want to share my version嗨,我想分享我的版本
public ActionResult List(string success,string error)
{
TempData["success"] = success;
TempData["error"] = error;
return View();
}
public ActionResult Add()
{
return RedirectToAction("List",new
{
error = "not added",
success = "added"
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.