Search code examples
c#asp.net-mvcasp.net-core-mvc-2.0

RedirectToAction and pass a value?


If I have a controller action to redirect to another action like so:

public ActionResult Index()
{
    RedirectToAction("Redirected", "Auth", new { data = "test" });
}

public ActionResult Redirected(string data = "")
{
    return View();
}

The URL bar will have something like "Redirected?data=test" in it, which AFAIK is the proper behavior. Is there a way I can pass a variable directly to the Redirected ActionResult without a change on the client?
I'd like to pass "test" directly to the Redirected ActionResult without the URL changing. I'm sure there's a simple way to do this, but it is escaping me. I know I can make a static variable outside the functions that I can pass the variable to and from, but that doesn't seem like a proper solution.


Solution

  • You can use TempData variable.

    public ActionResult Index()
    {
        TempData["AfterRedirectVar"] = "Something";
        RedirectToAction("Redirected", "Auth", new { data = "test" });
    }
    
    public ActionResult Redirected(string data = "")
    {
       string tempVar = TempData["AfterRedirectVar"] as string;
       return View();
    }
    

    This link could be helpful.