How to pass tempdata in RedirectToAction in ASP.Ne

2019-07-05 18:00发布

问题:

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.

回答1:

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


回答2:

See if this works:

public ActionResult Logoff()
{
    DoLogOff();
    ControllerContext.Controller.TempData["Message"] = "Success";
    return RedirectToAction("Index", "Home");
}


回答3:

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.