Monday, December 5, 2016

MVC Sessions

Sessions can be maintained in MVC by three ways: tempdataviewdata, and viewbag.

Temp Data - maintain data when you move from one controller to another controller or from one action to another action. When you redirect, it maintains data between those redirects. It internally uses session variables.

View Data - maintain data when you move from controller to view.

View Bag - It’s a dynamic wrapper around view data (2 or more). When you use Viewbag type, casting is not required. It uses the dynamic keyword internally.









Left: is for view bag. (Dynamic keywords)












Session variables - Maintain data from any entity to any entity.

Hidden fields and HTML controls - Maintain data from UI to controller only. So you can send data from HTML controls or hidden fields to the controller using POST or GET HTTP methods.

Maintains data betweenViewData/ViewBagTempDataHidden fieldsSession
Controller to ControllerNoYesNoYes
Controller to ViewYesNoNoYes
View to ControllerNoNoYesYes


What is the difference between TempData and ViewData ?
TempData maintains data for the complete request
ViewData maintains data only from Controller to the view.

What is the difference between ViewBag and ViewData ?
Both are used to communicate between controller and view.
ViewBag  is dynamic
ViewData is dictionary object.

Does TempData preserve data in the next request also?
TempData is dictionary object. is available throughout for the current request and in the subsequent request, it’s available depending on whether “TempData” is read or not.

So if TempData is once read it will not be available in the subsequent request.




No comments:

Post a Comment