Wednesday, 12 June 2013

MVC 4 ViewBag, ViewData and TempData

Model View Controller: MVC is a software architecture, which separates the logic from the user interface. This is achieved by separating the application into three parts Model, View and Controller. MVC is separation of concern. MVC is also a design pattern.
Model: Represents the logical behavior of data in the application. It represents applications business logic. Model notifies view and controller whenever there is change in state.
View: Provides the user interface of the application. A view is the one which transforms the state of the model into readable HTML.
Controller: Accepts inputs from the user and instructs the view and model to perform the action accordingly.

Advantages of MVC:
1)    Full control over HTML rendered. No renaming of HTML IDs.
2)    Provides clean separation of concerns (SoC).
3)    No ViewState (Stateless). 
4)    Enables Test Driven Development (TDD). 
5)    Easy integration with JavaScript frameworks.
6)    RESTful URLs that enables SEO. Representational state transfer URLs example User/Comment/1, which is user friendly, no URL rewriting required. 
7)    Integration on the client side becomes easy like using JavaScript, JQuery, Ajax, JSON.
8)    Supports multiple view engines (aspx, Razor)

 

 

ViewBag, ViewData and TempData:

ViewData:
1)    ViewData is a dictionary object that is derived from ViewDataDictionary class.
2)    ViewData is used to pass data from controller to corresponding view.
3)    Its life lies only during the current request.
4)    If redirection occurs then its value becomes null.
5)    It’s required typecasting for complex data type and check for null values to avoid error.

ViewBag:
1)    ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
2)    Basically it is a wrapper around the ViewData and also used to pass data from controller to corresponding view.
3)    Its life also lies only during the current request.
4)    If redirection occurs then its value becomes null.
5)    It doesn’t required typecasting for complex data type.

TempData:
1)    TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives session.
2)    TempData is used to pass data from current request to subsequent request means in case of redirection.
3)    Its life is very short and lies only till the target view is fully loaded.
4)    It’s required typecasting for complex data type and check for null values to avoid error.
5)    It is used to store only one time messages like error messages, validation messages.

No comments:

Post a Comment