Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

I had the same issue, and it turned out that we had made our SessionStateBehavior readonly, in an implementation of IControllerFactory. I changed this to default, and then got a subsequent error relating to Session State not being available and something about Registry keys... this error was solved on my local machine by starting the Asp.Net State Service in Windows Services.

TempData requires the use of Session State between requests.

Hope this helps someone.

Another factor of TempData not working is when your App is under a distributed system.

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