top of page

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.

  1. Hidden Field (Stored on the client side, this is not displayed on the browser).

  2. Cookies (Persistence and Non-Persistence). I don't like using cookies as much, because some users will turn them off.

  3. Query String (Very common, but I've been told not to use it very often).

  4. Session State - uses a session state object to store data throughout the user's session.

  5. Routes - Uses the URL to store data and pass it between requests. I think this can be very powerful.

  6. TempData - uses a session state object to store data until it is read. Similar to #4, Session State.

  7. ViewData - is part of the ViewDataDictionary type.

  8. 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.

bottom of page