When using ASP.NET MVC 3 Razor I couldn’t help but wonder… when should I use ViewBag vs. ViewData vs. TempData?

Finding an answer to this questions seemed oddly difficult. Different forums or blog posts contradicted each other. It’s not rocket science, but when you’re just getting started with MVC 3 it’s just one more thing that’s confusing.

No here is the shortest answer that I can come up with:

ViewData:

  • ViewData is a dictionary object that you put data into, which then becomes available to the view. ViewData is a derivative of the ViewDataDictionary class, so you can access by the familiar “key/value” syntax.

ViewBag:

  • The ViewBag object is a wrapper around the ViewData object that allows you to create dynamic properties for the ViewBag.

TempData

  • TempData is meant to be a very short-lived instance and only persists until the next request. Realistically, this meanss that TempData is only safe to use when redirecting.

Below is a code sample on how to use the ViewBag, ViewData and TempData objects, which populate an “active server” object that a view render’s on an IT maintenance page:

public class HomeController : Controller         
{             
// Sample             
public ActionResult Index()             
{                 
var activeServerNode = new ServerNode                
{                     
Name = "Marvin",                     
Location = "DataCenter 3",                    
 Description = "Webhost",                     
OnlineDate = DateTime.Today,                     
NextMaintenanceWindow = GetMaintenanceWindow("Marvin"),                     
NumberOfSitesHosted = 42,                     
NumberOfRedundantServers = 8                 
};                   

ViewData["ActiveServer"] = activeServerNode;                 
ViewBag.ServerNode = activeServerNode;                 
TempData["ActiveServer"] = activeServerNode;                   

return View();             
}         
}

The index.cshtml accesses and renders the object with the same syntax:

@using ServerStatus.Models; 
@{         
ViewBag.Title = "Home Page";     
var viewDataServer = ViewData["ActiveServer"] as Server;     
var tempDataServer = TempData["ActiveServer"] as Server;                 
}
<h2>Welcome to the Server Maintenace Page</h2>
<div><a href="/Products"><img src="@Url.Content("\\Content\\Images\\logo.jpg")" alt="Server Page" /> </a>
<div>The active server is <br />
<h4>@ViewBag.ServerNode.Name</h4>
<h3>@viewDataServer.Name</h3>
<h2>@tempDataServer.Name</h2>
</div>

For a more detailed post checkout this one: http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications

facebooktwittergoogle_plusredditpinterestlinkedinmail