Search code examples
asp.net-mvctempdatapost-redirect-get

MVC temp data persists through separate page requests?


It's been my understanding since I've been using it, that in MVC, anything you put in TempData is... well, temporary. It's only there for the duration of the current request, and then it's gone when the request is complete and the response is sent.

In order to preserve model state errors through a POST-Redirect-GET cycle, I used asgeo1's answer posted here:

ASP.NET MVC - How to Preserve ModelState Errors Across RedirectToAction?

I thought this worked well, but discovered in my latest project (VS 2015) that temp data actually persists.

Scenario: user enters a value into a text input in Search, submits a post and is redirected to another page, Index. Then they click a link back to Search.

Search.cshtml:

@model Foo.Models.TestModel

<form method="post" action="@Url.Content("~/Home/Search")">
    @Html.TextBoxFor(o => o.TestString)
    <input name="find" type="submit" value="Search" />
</form>

Index.cshtml:

<a href="@Url.Content("~/Home/Search")">Search</a>

Controller:

    [HttpGet]
    [RestoreModelStateFromTempData]
    public ActionResult Search(TestModel model)
    {
        //var modelState = TempData["ModelState"] as ModelStateDictionary;
        //if (modelState != null)
        //    throw new Exception("Temp Data should be empty.");
        return View(model);
    }

    [HttpPost]
    [SetTempDataModelState]
    public ActionResult Search(TestModel_Post model)
    {
        return RedirectToAction("Index", "Home", null);
    }

    [HttpGet]
    public ActionResult Index() { return View(); }

To my surprise, the temp data from the previous post is preserved, and the model state from that gets merged and the user sees the last value they entered. This is on a fresh navigation to that page - there should be no temp data here.

A workaround is to clear the model state if it's valid. But this was quite a shock to me - I don't feel I understand TempData any more.

What's going on here?


Solution

  • You are mistake between ViewData and TempData.

    ViewData only transfers data from controller to view, not vice-versa. It is valid only during the current request. ViewData is useful in transferring data from Controller to View.

    TempData in ASP.NET MVC can be used to store temporary data which can be used in the subsequent request. TempData will be cleared out after the completion of a subsequent request.

    TempData is useful when you want to transfer non-sensitive data from one action method to another action method of the same or a different controller as well as redirects