Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Wednesday, February 22, 2012

ASP.Net MVC 3 - passing data to view by ViewBag, ViewData, and TempData

      ViewBag, ViewData, and TempData are 3 vehicles to pass data from action method to a view. But it's confusing what the differences are between them and when to use which method to pass the data to view. I would like to share my understanding of this topic.

       1. ViewBag:

              ViewBag is a new feature introduced with MVC 3. This feature allows you to define any property on a dynamic object, which can be accessed through the Controller.ViewBag property in a view. And the better thing is you don't have to cast the property.

       2. ViewData:

              ViewData is similar to ViewBag, but it derives from ViewDataDictionary class. So you access the data by key/value style and have to cast the value to known type. The casting make ViewData less attractive comparing with ViewBag.

       3. TempData:

              TempData is similar to Session data. But the life of TempData is much shorter than Session. It lasts only one more request and will be marked for deletion once it is read. So TempData is usually used to keep the data across a redirection.

Sunday, February 19, 2012

Some differences between ASP.Net MVC 3.0 and ASP.Net MVC 2.0

   ASP.Net MVC, first released around year 2009, has evolved to 3.0 (as I am writing this article, 4.0 is on the way). As the history proved, any Microsoft technologies, tools, which upgrade to 3.0, are worth to take a serious look. I would like to introduce some differences between MVC 3 and 2:

       1. ASP.Net view engine is changed to Razor. One of the direct effects is: the ASP.Net notation (<% %>) is changed to new notation @.

       2. Master page is gone. Well..., not really. It is re-invented as layout page, e.g. _Layout.cshtml.

       3. Induced a new feature ViewBag to pass parameter from controller to view.

       4. Better support to dependency injection.

       5. Better support to JQuery

       Above items are only from practice point of view. If you want to get the full list of new features of MVC 3.0, please read ASP.Net MVC 3.0 document.