Manage Session In MVC

Manage Session In MVC

 

ASP.NET MVC provides three ways (TempData, ViewData and ViewBag) to manage sessions, apart from that we can use session variable, hidden fields and HTML controls for doing it. But like session variable these elements could not preserve values for all request, value persistence varies depending on the flow of request. For example, ViewData maintains data when you move from controller to view only.

 

 

 

 

TempData:

è TempData in ASP.NET MVC is basically a dictionary object derived from TempDataDictionary.

è TempData internally uses session variable and stays for a subsequent HTTP Request. This means it maintains data when you move one controller to another controller or one action to another action. As this is a dictionary object null checking and typecasting is required while using it.

è TempData gets destroyed immediately after it’s used (once value is read from tempdata) in subsequent HTTP request, so no explicit action required, if you want preserve value in the subsequent request after using need to call keep method or peak method. See the below example.

 

 

ViewData:

è ViewData maintains data when you move from controller to view. It is also a dictionary object and derived from ViewDataDictionary. As Data is stored as Object in ViewData, while retrieving, the data it needs to be Type Casted to its original type as the data is stored as objects and it also requires NULL checks while retrieving.

 

ViewBag

è The ViewBag is a dynamic type of property of ControllerBase class which is the base class of all the controllers. It’s a dynamic wrapper around ViewData casting is not required when you use ViewBag. ViewBag only transfers data from controller to view, not visa-versa. ViewBag values will be null if redirection occurs.

è ViewBag support any number of properties or values. if same value found then it will only consider last value assigned to the property.

 

As like ASP.NET session and Hidden fields can be used. session variables we can maintain data from any entity to any entity and hidden fields help to 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.

Previous Next

Start Your Data Journey Today With MSAInfotech

Take the first step towards data-led growth by partnering with MSA Infotech. Whether you seek tailored solutions or expert consultation, we are here to help you harness the power of data for your business. Contact us today and let’s embark on this transformative data adventure together. Get a free consultation today!

We utilize data to transform ourselves, our clients, and the world.

Partnership with leading data platforms and certified talents

FAQ Robot

How Can We Help?

Captcha

MSA Infotech