繁体   English   中英

如何在 ASP.Net MVC 的 RedirectToAction 中传递临时数据

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM