TempData not persisting

Fermin picture Fermin · Jul 28, 2009 · Viewed 8.9k times · Source

I have a controller that sets TempData before returning a view,

public ActionResult Edit(int id, int? order)
{
    Route route = new Route();
    // Do Work
    TempData["Route"] = route;
    return View(new FormViewModel(route, obj1, obj2));
}

This view contians a partial view with a link which goes to another action method called delete, the code for the delete link is:

<%= Html.ActionLink("Delete", "Delete", new { order = item.Order })%>

The code for the Delete action method is:

public ActionResult Delete(int order)
{
    Route route = (Route)TempData["Route"];
    // Do Work
}

The problem that I'm having is when I try to get TempData["Route"]; from the Delete action method is returning null.

I'm wondering if the issue is that this is a Get and not a Post? If so how can I do a Post to the Delete ActionMethod from within my form?

Answer

Darin Dimitrov picture Darin Dimitrov · Jul 28, 2009

TempData persist between two requests. What does the ReturnView method in your Edit action returns? As far as I can tell it is not a standard method defined in the Controller class. Are you redirecting in this method (i.e. returning a RedirectToRouteResult)?

Also are there any other requests that could occur between your Edit and Delete actions? For example ajax requests.

Generally it is not a good idea to use TempData to persist something for a long time. The pattern usually is the following:

public ActionResult Update() 
{
    // When you put something into the TempData dictionary you usually
    // redirect immediately to an action that will use the object stored
    // inside.
    TempData["something"] = "something";
    return RedirectToAction("success");
}

public ActionResult Success() 
{
    var something = TempData["something"];
    return View();
}

If you need to persist something for a longer time you should use Session.