Question

İn my MVC3 project, there is plenty of TempData[] that I am using for passing datas between actions. And it works totaly perfect when I use Chrome. But in IE I can't get values of TempData[] items. if anyone knows whats the problem and how can I solve it?`

public class SomeController : Controller
{
    public ActionResult SomeAction()
    {
        TempData["id"] = "someData";
        return View();

    }
}


public class AnotherController : Controller
{
    public ActionResult AnotherAction()
    {
        string data = Convert.ToString(TempData["id"]);
        return View();

    }
}

`

Was it helpful?

Solution

You should never return a view from a controller action that stores something into TempData. You should immediately redirect to the controller action that is supposed to use it:

public class SomeController : Controller
{
    public ActionResult SomeAction()
    {
        TempData["id"] = "someData";
        return Redirect("AnotherAction", "Another");
    }
}


public class AnotherController : Controller
{
    public ActionResult AnotherAction()
    {
        string data = Convert.ToString(TempData["id"]);
        return View();
    }
}

The reason for this is that TempData survives only for a single additional request. So for example if inside the view you are sending an AJAX request to some controller action (no matter which) and then have a link in this view pointing to the target action, when the user is redirected to this target action TempData will no longer exist since it was lost during the AJAX request done previously.

If you need to store data for longer than a single redirect you could use Session.

OTHER TIPS

If you need to store data for longer than a single redirect you should use Keep or Peek methods.

string data = TempData["id"].;
TempData.Keep("id");

or simply use,

string data = TempData.Peek("id").ToString();

Peek function helps to read as well as advice MVC to maintain “TempData” for the subsequent request.

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