In the Asp.net MVC 3 web application Program , viewdata and viewbag . Comparison:
| viewdata |
viewbag |
| it is a set of key/value dictionaries |
It is dynamic type |
| from Asp.net MVC 1 |
ASP. NET mvc3 |
| Based on ASP.net 3.5 framework |
Based on ASP.net 4.0 and. NET Framework |
| viewdata is faster than viewbag |
viewbag is slower than viewdata |
| the appropriate data type needs to be converted when querying data in viewpage |
type conversion is not required when querying data in viewpage |
| some types of conversions Code |
better readability |
Viewbag attributes:
PublicDynamic viewbag {Get{If(_ Dynamicviewdata =Null) {_ Dynamicviewdata=NewDynamicviewdatadictionary () =>Viewdata );}Return_ Dynamicviewdata ;}}
Viewdata attributes:
PublicViewdatadictionary viewdata {Get{If(_ Viewdata =Null) {Setviewdata (NewViewdatadictionary ());}Return_ Viewdata ;}Set{Setviewdata (value );}}
The specific example is as follows:
Use viewdata In the 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 " ] = 25 ;
Return View ();
}
The index. cshtml page corresponding to viewdata:
< P >
My name is < B > <% : Viewdata [ " Name " ] %> </ B > , < B > <% : Viewdata [ " Age " ] %> </ B > Years Old. < BR /> I like the following colors: </ 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 >
Use viewbug in 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; viewbag. Name = " Hajan " ; Viewbag. Age = 25 ; Return View ();}
The index. cshtml page corresponding to viewbug:
< 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 viewbag. listcolors ){ %> < Li > < Font Color = "<%: Color %>" > <% : Color %> </ Font >
</ Li >
<% } %>
</ Ul >
< P > <% : Viewbag. datenow %> </ P >