ViewData Vs ViewBag Vs TempData in MVC ( Differences )
ViewData:
- ViewData internally uses dictionary which derived from ViewDataDictionary to store data in Key value pairs.
- Its scope is carrying data from controller to a view but not controller to a controller.
- It needs to typecast while reading the data from ViewData.
Carrying data from Controller to a view:
Carrying data from Controller to Controller using ViewData:
ViewBag:
- ViewBag is almost equal to ViewData.
- ViewBag uses a new feature of C#4.0 called dynamic.
- Since ViewBag uses dynamic feature it wont be having intelligence. Property gets created on the fly.
- Internally ViewBag propertys are stored as key/value pairs of ViewDataDictionary.
- ViewBag also passes data from controller to a view but not controller to controller.
Passing data from controller to a view:
Passing data from controller to a controller:
TempData:
- TempData passes the data from Controller to controller and controller to view.
- Its life time is till to read in a view.
- Its life time can be extended by using Keep and Peek.
- Keep has 2 overload methods Keep() & Keep("TempDataName").
- Peek() dont have any overload method.
- Syntax: string str= TempData.Peek("Temp").ToString();
- It internally uses sessions.
Passing data from controller to view:
Passing data from Controller to a Controller:
Using Keep() to extend life time to further request:
TempData With out Keep:
No comments:
Post a Comment