How to pass tempdata in RedirectToAction in ASP.Ne

2019-07-05 17:58发布

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:

@Html.Partial("../Home/DisplayPreview")

DisplayPreview CSHTML File:

   @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:

   @TempData["Message"] 

But I want something like my first solution.

3条回答
Lonely孤独者°
2楼-- · 2019-07-05 18:25

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
查看更多
Melony?
3楼-- · 2019-07-05 18:25

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. 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.

查看更多
放我归山
4楼-- · 2019-07-05 18:26

See if this works:

public ActionResult Logoff()
{
    DoLogOff();
    ControllerContext.Controller.TempData["Message"] = "Success";
    return RedirectToAction("Index", "Home");
}
查看更多
登录 后发表回答