We already know that 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 are 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 the Controller's action, which is not directly accessible to view, and will be null once processed.
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 values of variables don't destroy from one page to another, but in a web application, the 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 an ASP.NET WebForms background, 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 one. But don't worry, we will learn each technique in great detail with real-world examples, keep your IDE open while going through the articles, and keep practicing side-by-side.
Read all the next sub-articles one by one, to grasp the concepts of the above techniques.