Maintaining State
As all web developers know, HTTP is a stateless protocol. Each HTTP request does not know about the previous request. Maintaining state has always been an issue.
In ASP.Net MVC, the most common ways to maintain data are:
The first four are common web programming features for maintaining state.
Routes and TempData are specific to ASP.Net Core MVC for maintaining state.
-
Hidden Field (Stored on the client side, this is not displayed on the browser).
-
Cookies (Persistence and Non-Persistence). I don't like using cookies as much, because some users will turn them off.
-
Query String (Very common, but I've been told not to use it very often).
-
Session State - uses a session state object to store data throughout the user's session.
-
Routes - Uses the URL to store data and pass it between requests. I think this can be very powerful.
-
TempData - uses a session state object to store data until it is read. Similar to #4, Session State.
-
ViewData - is part of the ViewDataDictionary type.
-
ViewBag - uses C# dynamic type to allow me to add properties.
An example using ViewData and ViewBag in the same controller.
ViewBag.Conferences = conferences;
ViewData["Divisions"] = divisions;
In the view:
<div class="col-sm-9">
<h3>@ViewData.Count items in ViewData</h3>
@foreach (KeyValuePair<string, object> item in ViewData)
{
<div>@item.Key - @item.Value</div>
}
</div>
​
I think ViewBag is easier to work with compared to ViewData.