State Management Technique in Asp.Net MVC

by Sachin Singh


Posted on Friday, 27 March 2020

Tags: State Management Technique in MVC How to pass data in MVC What is viewbag in mvc what is ViewData in MVC What is TempData in MVC TempData.Peek() TempData Keep method ASP.NET MVC State Management In ASP.NET ViewBag mvc ViewBag ViewBag in mvc ViewBag in asp.net mvc ViewBag in C# mvc what is ViewBag in mvc viewdata ViewData mvc ViewData ViewData in mvc ViewData in asp.net mvc mvc5 ViewData in C# mvc what is ViewData in mvc tempdata tempdata in mvc tempdata in asp.net mvc tempdata in C# mvc what is tempdata in mvc

We know HTTP is a stateless protocol and every request to the server is a fresh request. Once the request comes to the server, after processing, all the control's values and page information get destroyed from the server.

So, to persist data from one page to another page or across multiple requests to the same page we need to do some additional work, called state management.

In Asp.Net MVC we have Controller and View, So we need to pass data either from Controller to View or View to Controller or sometimes from one Action to another. In any of the above situations, we need to persist data that is the data we get in Controller's action is not directly accessible to view and will be null once processed, and needs to persist.

Below are the different state management techniques used in Asp.Net MVC.
  • ViewData
  • ViewBag
  • TempData and
  • Session variable

In a desktop application all requests are internal so there is no need for any state management technologies, The value of variables don't destroy from one page to another but in a web application story is different, here each request to the server is a fresh request and you can't get the values from the previous request to the current request, so somehow we need to maintain values across multiple requests

If you are coming from Asp.Net WebForm's background then you would know that to maintain the state we had ViewState and Application variables, In Asp.Net MVC we don't have ViewState or Application variables but we have more effective alternatives. Cookies and Sessions are also available which can be used to save user-related information. But, each of the techniques has its own advantages and disadvantages, you need to be very careful while selecting the technique. But, don't worry we will learn each technique in great detail with real-world examples, just keep your IDE open while going through the articles and keep practicing side beside.

Read all the next sub-articles one by one, to grasp the concepts of the above techniques.