Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewBag, ViewData, TempData, Session - how and when to use them?

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()); 
   }
like image 268
Adam Bielecki Avatar asked Mar 04 '13 14:03

Adam Bielecki


People also ask

When to use Viewdata viewbag and tempdata in MVC?

In ASP.NET MVC there are three ways - ViewData, ViewBag and TempData to pass data from controller to view and in next request. Like WebForm, you can also use Session to persist data during a user session. Now question is that when to use ViewData, VieBag, TempData and Session. Each of them has its own importance.

What is the difference between viewbag and Viewdata in Salesforce?

The scope of ViewBag is permitted to the current request and the value of ViewBag will become null while redirecting. ViewData is a dictionary object to pass the data from Controller to View where data is passed in the form of key-value pair.

What is the use of viewbag in MVC?

ViewBag is used to pass data from controllers to views. ViewBag has a short life means once it passed value from controllers to views, it becomes null. ViewBag doesn't require typecasting. 1. Open Visual Studio and Create a New MVC 5 Project.

What is the difference between Viewdata and tempdata?

The scope of ViewData is similar to ViewBag and it is restricted to the current request and the value of ViewData will become null while redirecting. TempData is a dictionary object to pass the data from one action to other action in the same Controller or different Controllers.


1 Answers

ViewBag, ViewData, TempData, Session - how and when to use them?

ViewBag

Avoid it. Use a view model when you can.

The reason is that when you use dynamic properties you will not get compilation errors. It's really easy to change a property name by accident or by purpose and then forget to update all usages.

If you use a ViewModel you won't have that problem. A view model also moves the responsibility of adapting the "M" (i.e. business entities) in MVC from the controller and the view to the ViewModel, thus you get cleaner code with clear responsibilities.

Action

public ActionResult Index()
{
    ViewBag.SomeProperty = "Hello";
    return View();
}

View (razor syntax)

@ViewBag.SomeProperty

ViewData

Avoit it. Use a view model when you can. Same reason as for ViewBag.

Action

public ActionResult Index()
{
    ViewData["SomeProperty"] = "Hello";
    return View();
}

View (razor syntax):

@ViewData["SomeProperty"]

Temp data

Everything that you store in TempData will stay in tempdata until you read it, no matter if there are one or several HTTP requests in between.

Actions

public ActionResult Index()
{
    TempData["SomeName"] = "Hello";
    return RedirectToAction("Details");
}


public ActionResult Details()
{
    var someName = TempData["SomeName"];
}
like image 120
jgauffin Avatar answered Oct 31 '22 03:10

jgauffin