What's the difference between ViewData and ViewBag?
I saw the ViewBag
in MVC 3. How's that different than ViewData
in MVC 2?
Solution 1:
It uses the C# 4.0 dynamic feature. It achieves the same goal as viewdata and should be avoided in favor of using strongly typed view models (the same way as viewdata should be avoided).
So basically it replaces magic strings:
ViewData["Foo"]
with magic properties:
ViewBag.Foo
for which you have no compile time safety.
I continue to blame Microsoft for ever introducing this concept in MVC.
The name of the properties are case sensitive.
Solution 2:
Internally ViewBag properties are stored as name/value pairs in the ViewData dictionary.
Note: in most pre-release versions of MVC 3, the ViewBag property was named the ViewModel as noted in this snippet from MVC 3 release notes:
(edited 10-8-12) It was suggested I post the source of this info I posted, here is the source: http://www.asp.net/whitepapers/mvc3-release-notes#_Toc2_4
MVC 2 controllers support a ViewData property that enables you to pass data to a view template using a late-bound dictionary API. In MVC 3, you can also use somewhat simpler syntax with the ViewBag property to accomplish the same purpose. For example, instead of writing ViewData["Message"]="text", you can write ViewBag.Message="text". You do not need to define any strongly-typed classes to use the ViewBag property. Because it is a dynamic property, you can instead just get or set properties and it will resolve them dynamically at run time. Internally, ViewBag properties are stored as name/value pairs in the ViewData dictionary. (Note: in most pre-release versions of MVC 3, the ViewBag property was named the ViewModel property.)
Solution 3:
ViewBag vs ViewData in MVC
http://royalarun.blogspot.in/2013/08/viewbag-viewdata-tempdata-and-view.html
Similarities between ViewBag & ViewData :
Helps to maintain data when you move from controller to view. Used to pass data from controller to corresponding view. Short life means value becomes null when redirection occurs. This is because their goal is to provide a way to communicate between controllers and views. It’s a communication mechanism within the server call.
Difference between ViewBag & ViewData:
ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0. ViewData requires typecasting for complex data type and check for null values to avoid error. ViewBag doesn’t require typecasting for complex data type.
ViewBag & ViewData Example:
public ActionResult Index()
{
ViewBag.Name = "Arun Prakash";
return View();
}
public ActionResult Index()
{
ViewData["Name"] = "Arun Prakash";
return View();
}
Calling in View
@ViewBag.Name
@ViewData["Name"]
Solution 4:
ViewData
: It requires type casting for complex data types and checks for null values to avoid errors.
ViewBag
: It doesn’t require type casting for complex data types.
Consider the following example:
public class HomeController : Controller
{
public ActionResult Index()
{
var emp = new Employee
{
EmpID=101,
Name = "Deepak",
Salary = 35000,
Address = "Delhi"
};
ViewData["emp"] = emp;
ViewBag.Employee = emp;
return View();
}
}
And the code for View
is as follows:
@model MyProject.Models.EmpModel;
@{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = "Welcome to Home Page";
var viewDataEmployee = ViewData["emp"] as Employee; //need type casting
}
<h2>Welcome to Home Page</h2>
This Year Best Employee is!
<h4>@ViewBag.Employee.Name</h4>
<h3>@viewDataEmployee.Name</h3>
Solution 5:
All answers suggest that ViewBag
and/or ViewData
is to pass data from Controller
to Views
which is misinformation. both are very useful to pass data from Views to Layout or Partial to Views (or ViewComponents, etc) It's not controller exclusive.
as the default asp.net sample have this in the layout page:
<title>@ViewData["Title"] - MyApp</title>
and in any view
ViewData["Title"] = "Details";
So then, to asking the question: "what's the difference between ViewBag
and ViewData
?"
The most notable difference is ViewData
is a Strongly Typed Dictionary while
ViewBag
is a dynamic type.
Note that the data inside IS THE SAME
ViewData["Title"] = "MyTitle";
ViewBag.Title; // returns "MyTitle";
When to use one or another?
-
ViewBag
doesn't support not valid C# names. you can't accessViewData["Key With Space"]
withViewBag
-
ViewBag.Something
is dynamic and you may have problems when calling methods (like extension methods) that needs to know the exact parameter at compile time. -
ViewBag
can check for nulls syntactical cleaner:ViewBag.Person?.Name
-
ViewData
have all the properties of a Dictionary likeContainsKey
,Add
, etc. so you can useViewData.Add("somekey", "somevalue")
keep in mind it might throw exceptions. - Using
ViewData
on views needs TypeCasting whileViewBag
don't.
Knowing the subtle differences, using one or another is much more a taste preference.
Normally you can think of ViewBag.AnyKey
to an alias of ViewData["AnyKey"]