How to pass tempdata to RedirectToAction in ASP.Net MVC

I need to pass one successful exit message in one of the views, but I cannot do this. Here is what I have.

The solution does not work:

 //LogController:
  public ActionResult Logoff()
  {
      DoLogOff();
      TempData["Message"] = "Success";
      return RedirectToAction("Index", "Home");
  }

  // HomeController
  public ActionResult Index()
  {
      return View();
  }

CSHTML Index 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();
}

CSHTML Index File:

   @TempData["Message"] 

But I want something like my first decision.

+1
source share
3 answers

See if this works:

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

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 the form:

@ViewBag.Message
0
source

, DoLogOff(), , , , , (, TempData), . , .

What you can try is to simply pass the flag to your index, which will show the message with the message disabled, if present. I would NOT use a string message, for example, you are showing in your โ€œworkingโ€ example, because it can be attacked by cybercriminals to redirect people to malicious sites.

0
source

All Articles