TempData value not persisting if used in view

user952072 picture user952072 · Aug 28, 2013 · Viewed 8.9k times · Source

I am using

TempData["hdn"] = "1";

in controller

If I use this

 @{
      var hdn = (string)TempData["hdn"];
  }

in View, TempData["hdn"] value in getting null in POST. If I skip this code in view it persists in POST. Why this is happening?

Answer

Slicksim picture Slicksim · Aug 28, 2013

TempData values are cleared after they are read.

if you want the value back in the controller after you have read it in the view, then you will need to include it in a hidden field and then read it out from the form values.

something like:

<input type="hidden" name="hdn" value="@hdn" />

Then in your controller, you can do:

var hdn = Request.Form["hdn"]

HTH