Search code examples
asp.net-mvc-4tempdata

TempData value not persisting if used in view


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?


Solution

  • 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