Hello everyone, I am going to share the
difference between ViewData vs. ViewBag vs. TempData and also TempData.Keep()
vs. TempData.peek() methods in ASP.Net MVC.
ViewData
: View Data is a dictionary object and use to maintain the
data between the controller to View.
It's also require to typecasting and It check
null value each time.
It become null if redirect occurs.
ViewBag
: View bag is a dynamic property and use to maintain the
data between the controller to View.
It's not require to typecasting and check null
value.
It become null if redirect occurs.
TempData: Temp
Data is a dictionary object and use to
maintain the data between the controller to controller and one action to other
action.
It use to check null value each time.
The TempData.keep()
and TempData.peek() methods are use
to read the data without deletion the current read objects.
TempData.Peek()
use to hold or prevent the value for another request.
TempData.Keep()
use
to hold or prevent the value depends on your additional logic.
TempData.Keep()
have two overloading methods. i.e.
1.
void keep() [data not deleted after completed
request.]
2.
void keep(string key) [data
not deleted after completed request and persist data by specific name]
TempData.Peek() no overloaded methods.
i.e.
1.
object peek(string key) [return
an object with specific key without key deletions.]
Session
Variables:
This is use to maintain data between one entity
to other entity.