Tuesday 12 July 2011

ViewBag v/s ViewData


Hi Friends,
If you go through ASP.NET MVC 3.0 framework then you will find  two frequently  used collection of data object which  used to pass data between control and views  and partial views. as both are doing similar functionality but has  some difference in that , so today , I would like to  put some difference of those and interoperability of that .



ViewData
ViewBag
It is dictionary of name/value pair  collection
It is dynamic  type object
This features exist since 1st release of ASP.NET MVC
This features available from ASP.NET MVC 3.0
This will work  in ASP.NET with .net 3.5 framework and above
This will work well with ASP.NET 4.0  with .net 4.0 framework and above
ViewData is faster compare to ViewBag   
ViewBag is slower than ViewData
While retrieving  data from viewData in to view pages , one need to do proper type casting
While retrieving  data from viewbag in to view pages , one need  not to do  type casting
Hence it make code with lots of  type casting  fragments
Hence it make more clear code


ViewData :
    ViewData in  Controler

    ViewData in  Razor View


View Bag :
  View Bag in  Controler

 View Bag  in  Razor View


These are some difference  of that. but actually they are interoperable in ASP.NET 4.0 environment.  means if  you can use viewbag to  take  data from  controller and  render in view using  viewdata  and vice verse.
let me explain
now  I  used  viewdata in  Controler to  take data


and  render data using viewbag in Razor view

now  I  used  viewbag in  Controler to  take data


and  render data using viewdata  in Razor view



to  check out  this  here I have attached it's source code.
Please find the same.




No comments:

Post a Comment