In MVC 3, there is a new ViewBag dynamic feature, which is intended primarily for use in the viewdata[] dictionary classes that are used to pass values from controller to view. For ViewBag is so powerful that you can dynamically set/get values, add any number of extra fields without requiring strong type detection.
To see these differences (and without viewbag), let's look at the examples:
Eample:--using ViewBag
Controller
Public ActionResult Index ()
{
list<string> colors = new list<string> ();
Colors. ADD ("Red");
Colors. ADD ("green");
Colors. ADD ("Blue");
viewdata["listcolors"] = colors;
viewdata["Datenow"] = DateTime.Now;
viewdata["name"] = "Hajan";
Viewdata["age"] = =;
return View ();
}
View (ASPX view Engine)
P>
My name is <b><%: viewdata["name"%></B>, <b><% : viewdata[' age ']%></b> years old. <br/>
I like the following colors:
modified </p> <ul id= "Colors" > <% foreach (var color in viewdata["Listcolors"] as list<string>) {%> <li > <font color= "<%: Color%>" ><%: Color%></font> </li> <%}%> </ul> <p> <%: viewdata["Datenow "]%> </p>
Eample:-using ViewBag
Controller
Public ActionResult Index () { list<string> colors = new list<string> (); colors. ADD ("Red"); colors. ADD ("green"); colors. ADD ("Blue"); viewbag.listcolors = Colors//colors is List viewbag.datenow = DateTime.Now;
Ten viewbag.name = "Hajan";
One viewbag.age =;
return View ();
13}
Do you see the difference between you and the above?
View (ASPX view Engine)
<p> my
name is
<b><%: Viewbag.name%></b>,
<b><%: Viewbag.age%>< /b> years old.
<br/>
I like the following colors:
</p>
<ul id= "Colors" >
<% foreach (var color in V iewbag.listcolors) {%>
<li>
<font color= "<%: Color%>" ><%: Color%></font>< C10/></li>
<%}%>
</ul>
<p>
<%: Viewbag.datenow
%> </p >
In the above example ViewBag is dynamic, so I don't need to convert viewbag.listcolors into a form like list<string>. On the other hand, this viewdata["key" is one of the other.
If you use the viewdata["Listcolors"]=colors in your controller, you can retrieve them by viewbag.listcolors in the view attempt.