ViewData, ViewBag, TempData and session - how to use them in Asp.NET MVC



ViewData and ViewBag allows you to access any data in view that was passed from controller.


The main difference between those two is the way you are accessing the data.
In ViewBag you are accessing data using string as keys - ViewBag[“numbers”]
In ViewData you are accessing data using properties  - ViewData.numbers. 


ViewData example

CONTROLLER

var Numbers = new List<int> { 1, 2, 3 };

            ViewData["numbers"] = Numbers;

VIEW


 <ul>
     @foreach (var number in (List<int>)ViewData["numbers"])
     {
         <li>@number</li>
     }
    
     </ul>

ViewBag example

CONTROLLER

var Numbers = new List<int> { 1, 2, 3 };

            ViewBag.numbers = Numbers;

VIEW

<ul>
     @foreach (var number in ViewBag.numbers)
     {
         <li>@number</li>
     }
    
 </ul>


Session is another very useful object that will hold any information.

For instance when user logged in to the system you want to hold his authorization level.

// GetUserAuthorizationLevel - some method that returns int value for user authorization level.

Session["AuthorizationLevel"] = GetUserAuthorizationLevel(userID);


This information will be stored in Session as long as user session is active.
This can be changed in Web.config file:

<system.web>
      <sessionState mode="InProc" timeout="30"/>

So then in controller inside the action :

public ActionResult LevelAccess()
        {
            if (Session["AuthorizationLevel"].Equals(1))
            {
                return View("Level1");
            }

            if (Session["AuthorizationLevel"].Equals(2))
            {
                return View("Level2");
            }

            return View("AccessDenied");
        }



TempData is very similar to ViewData and ViewBag however it will contain data only for one request.

CONTROLLER

// You created a method to add new client.

TempData["ClientAdded"] = "Client has been added";


VIEW

  @if(TempData["ClientAdded"] != null)
    {
       <h3>@TempData["ClientAdded"] </h3>
    }


TempData is useful when you want to pass some information from View to Controller. For instance you want to hold time when view was requested.

VIEW

@{
TempData["DateOfViewWasAccessed"] = DateTime.Now;
}

CONTROLLER

  if (TempData["DateOfViewWasAccessed"]!= null)
  {
     DateTime time = DateTime.Parse(TempData["DateOfViewWasAccessed"].ToString());
  }



Comments