Introduction: In this article i am going to
explain the use of ViewBag, ViewData and TempData to pass data from controller
to view to render a response back to a client in Asp.net MVC.
Description: In previous articles i explained. What is ViewBag, ViewData and TempData and What is Asp.Net MVC? Its work flow,goals and advantages and Difference between Asp.Net Webforms and Asp.Net MVC and MVC 4 application to Create,Read,Update,Delete and Search functionality using Razor view engine and Entity Framework
Implementation: Hope you have read my previous article
explaining ViewBag, ViewData and TempData (Link given in description section
above). So we can move further with the practical implementation to understand
their use.
·
Launch Visual studio-> File menu -> New -> Project ->
select Visual C# or Visual basic -> Select ASP.NET MVC 4 Web Application and
name the application "MvcDemoApp" or whatever you want.
·
A "New ASP.NET MVC 4 Project "dialog box will open ->
Select "Empty" template and leave the "razor " as the
default View engine.
·
Now it's time to create the controller. So in the solution
explorer right click on the Controller folder -> Add -> Controller ->
name the controller "HomeController" and leave the template
"Empty MVC controller" as it is and click on Add button.
·
Now in the Index action of the "HomeController"
controller we will use ViewBag to store the data that will be passed to the
view to be rendered. So let's create the view by right clicking in between the
Index action and select Add View -> leave all the settings as it is and
click on Add button.
·
Below is the snapshot of the controller code, View code and the
rendered output. Note: "HomeController.cs" is the controller and
"Index.cshtml" is the corresponding view.
What is ViewBag?
ViewBag and ViewData both
are used for the same purpose i.e. to transfer data from controller to view but
ViewBag comes with an additional feature that the type casting for complex
objects is not required.
ViewBag is a dynamic property
that takes advantage of the new dynamic features in C# 4.0. By dynamic we mean
that we can add properties to it in the controller, and read them later in the
view.
Example demonstrating the use of ViewBag
Click on the image to enlarge. |
In above example Company Name, location and list of
branches is passed from controller to view using ViewBag.
What is ViewData?
ViewData is an in-built
dictionary object that is derived from ViewDataDictionary class that can be
accessed and set with string type key values. It is a used to pass data from
Controller to View.
The data is only alive for one request and cannot persist between
requests i.e. if redirection occurs then its value becomes null. The problems
with ViewData are that the type casting is required 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.
Example demonstrating the use of ViewData
ViewData can also be used to
pass data from controller to view similar to ViewBag for the same purpose as
shown above.
Below is the snapshot of the Controller code, View code and the rendered output. Note: "HomeController.cs" is the controller and "Index.cshtml" is the corresponding view. Click on the below image to enlarge.
Company Name, its location and
list of branches is passed from controller to view using ViewData.
So from the above two examples
we saw that both the ViewBag and ViewData is used to pass the data from
controller to view but type casting is required while accessing the data from
the ViewData.
So we need to type cast
ViewData["CityList"] to List<String>
ViewData["CityList"] or we can also type cast it to
IEnumerable<String> ViewData["CityList"].
What is TempData?
The problem with the ViewData
and ViewBag for transferring data from controller to view is that the data is
only alive for current request. The data is lost if a redirection takes place
i.e. if one Action redirects to another action.
But when we need to persist the data between actions/redirection then asp.net MVC offers another dictionary object called TempData for that purpose.
It helps to maintain the data
when we move from one controller to another controller or from one action to
another action.It requires typecasting for complex data type and checks for
null values to avoid error.
It is derived from
TempDataDictionary and created on top of session. It will live till the
redirected view is fully loaded.
Example demonstrating the use of TempData
- Right click on Models folder -> Add -> Class and name it "BookDetails.cs" and write the code as shown in image below:
- Now create the controller and add the code in the controller to store the data in the TempData as shown in image below:
Click on the image to enlarge. |
- In above example, we stored book object in TempData in Controller’s Index Action and retrieved that in Controller’s another Action “DisplayBookData” that will render the Book Details . Do you think it can be done using ViewBag or ViewData? Actually No because if we try to do the same using ViewBag or ViewData, we will get null in Controller’s action “DisplayBookData” because only TempData object maintains data between controller actions.
- Now create two view corresponding to Index() and DisplayBookData() actions defined in HomeController. There is no need to write any code in the index.cshtml view because that will not render any details instead we write the code on DisplayBookData.cshtml view as shown in image below:
Click on the image to enlarge. |
- Now run the application. Output will be as shown in image below:
Now over to you:
A blog is nothing without reader's feedback and comments. So please provide your valuable feedback so that i can make this blog better and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linkedin and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates.
2 comments
Click here for commentshi
Replycan u provide download link for this project?
nice
ReplyIf you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..