In MVC ASP.NET there are three ways ViewData, ViewBag and TempData to pass data from controller
to view and in next request. Like WebForm, we can also use Session to persist
data during a user session.
ViewData and ViewBag are almost similar and TempData
performs some additional responsibility.
All this objects are available as properties of both the
view and controller. We can use this objects for the purposes of transporting amounts
of data from and to specific locations (e.g., controller to view or between
views).
In Detail:-
1.
ViewData
ViewData is a dictionary object
that is derived from ViewDataDictionary class that can be accessed and set with
string type key values as,
ViewData["KEY"] = "Value";
The data is only alive for one
request and cannot persist between requests, in other words if redirection
occurs then its value becomes null. ViewData required type casting for complex
data types at the location where the data is being extracted and also we need
to check for null values to avoid errors.
2. ViewBag
ViewBag
is a dynamic property that takes advantage of the new dynamic features in C#
4.0. Basically it is a wrapper around the ViewData that allows you to create
dynamic properties for the ViewBag and also used to pass data from controller
to corresponding view.
ViewBag comes with an additional
feature that the type casting for complex objects is not required. Similar
to viewdata it’s life also lies only during the current request.
Use in code: - ViewBag.Key
= "Value";
3. TempData
TempData
is a dictionary object that is derived from TempDataDictionary class and stored
in short lives session, created on top of the session.
The
problem with the ViewData and ViewBag is that the data is only alive for the
current request, i.e. data is lost if a redirection occurs, in other words if
one Action redirects to another action.
When we need to persist the data between
actions/redirections then ASP.NET MVC offers TempData for that purpose. It
will live until the redirected view is fully loaded. It’s required typecasting
for getting data and check for null values to avoid error.
In Code: - TempData["KEY"] = "Value";
When to use......?
Both the ViewData and ViewBag objects work well and
can be used in the following scenarios:-
- Binding dropdown lists.
- Components like a shopping cart
- To change/manipulate some data/text on view dynamically depending on action.
While the TempData object works well in one basic
scenario:-
- Passing data between the current and next HTTP requests/Action
- Store only one time messages like error messages, validation messages.
Comments
Post a Comment