Earlier today Scott Guthrie announced the ASP.NET MVC 3 - Release Candidate 2. I installed the new version right after the announcement, since I'm looking forward to see the new features. Among the other cool features included in this release candidate, there is a new ViewBag dynamic Views that can be used to pass data controllers as well as you use ViewData dictionary []. What is great and beautiful ViewBag (despite the name) is that its a dynamic type, which means that you can dynamically get/set values and add any number of additional fields without the need of strongly typed classes.
To see the difference, take a look at the following examples.
Example - in ViewData
Controller
{
The list of colors
Colors.Add ("Red");
Colors.Add ("green");
Colors.Add ("Blue");
ViewData ["listColors"] = colors.
ViewData ["dateNow"] = DateTime.Now.
ViewData ["name"] = "Hajan".
ViewData ["age"] = 25;
Back to View().
}
View (ASPX see Engine)
My name is
<%: ViewData["name"] %>,
<%: ViewData["age"] %>years old.
I love the following colours:
<%: color %>
<% foreach (var color in ViewData["listColors"] as List
<% } %>
<%: ViewData["dateNow"] %>
(I know the code might look more like own knife display engine, but few important right? point)
Example - using ViewBag
Controller
{
The list of colors
Colors.Add ("Red");
Colors.Add ("green");
Colors.Add ("Blue");
ViewBag.ListColors = color. //Colors is list
ViewBag.DateNow = DateTime.Now.
ViewBag.Name = "Hajan".
ViewBag.Age = 25;
Back to View().
}
You can see the difference?
View (ASPX see Engine)
My name is
<%: ViewBag.Name %>,
<%: ViewBag.Age %>years old.
I love the following colours:
<%: color %>
<% foreach (var color in ViewBag.ListColors) { %>
<% } %>
<%: ViewBag.DateNow %>
In my example, now I must cast ViewBag.ListColors list ViewBag is dynamic! On the other hand the ViewData ["key"] is object.
I would like to note that if you use ViewData ["ListColors"] = color;in your controller, you can retrieve the view to ViewBag.ListColors.
In both cases is
No comments:
Post a Comment