![](/img/trans.png)
[英]RedirectToAction is not working with Tempdata - ASP.net core MVC
[英]How to pass tempdata in RedirectToAction in ASP.Net MVC
我需要在其中一個視圖中傳遞一條注銷成功消息,但我無法這樣做。 這就是我所擁有的。
不工作解決方案:
//LogController:
public ActionResult Logoff()
{
DoLogOff();
TempData["Message"] = "Success";
return RedirectToAction("Index", "Home");
}
// HomeController
public ActionResult Index()
{
return View();
}
索引 CSHTML 文件:
@Html.Partial("../Home/DisplayPreview")
顯示預覽 CSHTML 文件:
@TempData["Message"]
工作解決方案
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();
}
索引 CSHTML 文件:
@TempData["Message"]
但我想要我的第一個解決方案。
在控制器中;
public ActionResult Index()
{
ViewBag.Message = TempData["Message"];
return View();
}
public ActionResult Logoff()
{
DoLogOff();
TempData["Message"] = "Success";
return RedirectToAction("Index", "Home");
}
然后你可以在視圖中使用它;
@ViewBag.Message
看看這是否有效:
public ActionResult Logoff()
{
DoLogOff();
ControllerContext.Controller.TempData["Message"] = "Success";
return RedirectToAction("Index", "Home");
}
由於您沒有顯示 DoLogOff() 的作用,我的猜測是您正在放棄會話,這意味着存儲在會話中的任何數據(如 TempData)都將丟失。 在下一頁刷新之前不會生成新會話,因此它不起作用。
您可能嘗試的只是將一個標志傳遞給您的索引視圖,如果它存在,它將顯示已注銷的消息。 我不會使用字符串消息,就像您在“工作”示例中顯示的那樣,因為攻擊者可以利用它來將人們重定向到惡意站點。
嗨,我想分享我的版本
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.