Introduction
In this article I explain the use of ViewBag, ViewData and TempData to pass data from a Controller to a View to render back to a client Asp.MVC.
Implementation
Launch Visual Studio then select "File" -> "New" -> "Project..." then select Visual C# or Visual Basic then 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 "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 then select "Add" -> "Controller" then name the controller "HomeController" and leave the template "Empty MVC controller" as it is and click on the Add button.
Now in the Index action of the "HomeController" controller we will use a ViewBag to store the data that will be passed to the view to be rendered. So let's create the view by right-clicking between the Index action and select Add View then leave all the settings as they are and click on the Add button.
The following 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 a Viewbag?
ViewBag and ViewData are used for the same purpose, to transfer data from the Controller to the 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. About Dynamic Data Types please read my first and previous article here Dynamic Data Type in C# , in this context by dynamic we mean that we can add properties to it in the controller and read them later in the view.

What is ViewData?
ViewData is a built-in dictionary object that is derived from the ViewDataDictionary class that can be accessed and set with string type key values. It is used to pass data from a Controller to a View.
The data is only alive for one request and cannot persist between requests, in other words 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.






Sonu ChaudharyPosted May 26, 2016, 10:21 AM
good one
Humayun Kabir MamunPosted May 26, 2016, 1:49 AM
Nice...
Vignesh ManiPosted May 25, 2016, 8:22 AM
Nice
RajaPosted May 25, 2016, 4:53 AM
Good Work...
Gowtham RajamanickamPosted May 25, 2016, 1:13 AM
Good one..
Muhammad Aqib ShehzadPosted May 25, 2016, 12:49 AM
nice dear
Munesh SharmaPosted May 25, 2016, 12:25 AM
good one
Thiruppathi RPosted May 24, 2016, 3:40 PM
Nice..
Debasis SahaPosted May 24, 2016, 1:45 PM
Good One..
Sonu ChaudharyPosted May 24, 2016, 12:45 PM
good one
Kuppurasu NagarajPosted May 24, 2016, 12:02 PM
Nice Sharing..