Question

I am calling a controller from more than one page and am using a returnUrl parameter to return the correct calling location:

public ActionResult EmailOrder(int id, string returnUrl)
{
    var message = "The order has been emailed";
    if (!string.IsNullOrEmpty(returnUrl)) return Redirect(returnUrl);
    return RedirectToAction("Details", new { id, message });
}

How can I pass additional information back to the view when using Redirect(url)? In the above example, I want to be able to pass message back when returnUrl has a value.

Was it helpful?

Solution

If you are redirecting to another action method and you want to pass data that can be access in the new action method, you should use the ASP.MVC Controller TempData property. You use this as follows:

[HttpPost]
public ActionResult MyActionMethod(Order order) 
{
    // write your logic here to save the Order
    TempData["message"] = "here is some message";
     return RedirectToAction("Index");
}

Data in the TempData member will be preserved across a redirection. It will be accessible in the redirected page, and then will be removed. Once you read an entry in TempData, it will be marked for deletion.

public ActionResult RedirectedMethod() 
{
    //Retrieve data from TempData.  It will then be marked for deletion
    var data = TempData["message"].ToString();
}

If you want to get a value without marking it for deletion, you can use the "Peek" method:

var data = TempData.Peek("message")

Also, you can manually preserve a value that would otherwise be deleted by using the "Keep" method:

TempData.Keep("message")

TempData is of type TempDataDictionary.

Note that TempData uses ASP.Net Session state behind the scenes, so you must have session state turned on if you are using TempData.

For more information on TempData, see here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top