Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 897
user952072 Avatar asked Aug 28 '13 11:08

user952072


3 Answers

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

like image 118
Slicksim Avatar answered Sep 27 '22 17:09

Slicksim


TempData is like ViewData but with a difference. It can contain data between two successive requests, after that they are destroyed.

If you want to keep TempData value the use

TempData.Keep()

Example:

var hdn= TempData["hdn"]; //it is marked for deletion
TempData.Keep("hdn"); //unmarked it

MSDN Docs for Keep

like image 32
Satpal Avatar answered Sep 27 '22 17:09

Satpal


A TempData key & value set will be deleted after it has been called. Satpal talked about Keep, but you can also use Peek if you want to be explicit about every time you want to retrieve it without having it deleted.

TempData.Peek(String)

Example:

var hdnNotDeleted = TempData.Peek["hdn"];

MSDN Documentation for Peek

like image 42
PChristianFrost Avatar answered Sep 27 '22 18:09

PChristianFrost