0% found this document useful (0 votes)
3 views

MVC 6 Viewbag and Viewdata

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

MVC 6 Viewbag and Viewdata

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

ASP.

NET MVC - ViewBag


ViewBag can be useful when you want to transfer temporary data
(which is not included in model) from the controller to the view. The
viewBag is a dynamic type property of ControllerBase class which is
the base class of all the controllers.

The following figure illustrates the ViewBag.

ViewBag
Note:
ViewBag only transfers data from controller to view, not visa-versa.
ViewBag values will be null if redirection occurs.
The following example demonstrates how to transfer data from
controller to view using ViewBag.

Example: Set ViewBag in Action method


namespace MVC_BasicTutorials.Controllers
{
public class StudentController : Controller
{
IList<Student> studentList = new List<Student>() {
new Student(){ StudentID=1, StudentName="Steve",
Age = 21 },
new Student(){ StudentID=2, StudentName="Bill",
Age = 25 },
new Student(){ StudentID=3, StudentName="Ram",
Age = 20 },
new Student(){ StudentID=4, StudentName="Ron",
Age = 31 },
new Student(){ StudentID=5, StudentName="Rob",
Age = 19 }
};
// GET: Student
public ActionResult Index()
{
ViewBag.TotalStudents = studentList.Count();

return View();
}

}
}
In the above example, we want to display the total number of
students in a view for the demo. So, we have attached the
TotalStudents property to the ViewBag and assigned the student
count using studentList.Count() .

Now, in the Index.cshtml view, you can access


ViewBag.TotalStudents property and display all the student info as
shown below.

Example: Acess ViewBag in a View


<label>Total Students:</label> @ViewBag.TotalStudents
Output:
Total Students: 5
ViewBag doesn't require typecasting while retriving values from it.

Points to Remember :
1. ViewBag transfers data from the controller to the view, ideally
temporary data which in not included in a model.
2. ViewBag is a dynamic property that takes advantage of the new
dynamic features in C# 4.0
3. You can assign any number of propertes and values to ViewBag
4. The ViewBag's life only lasts during the current http request.
ViewBag values will be null if redirection occurs.
5. ViewBag is actually a wrapper around ViewData.

ASP.NET MVC - ViewData


ViewData is similar to ViewBag. It is useful in transferring data from
Controller to View.

ViewData is a dictionary which can contain key-value pairs where


each key must be string.

The following figure illustrates the ViewData.

ViewData
Note:
ViewData only transfers data from controller to view, not vice-
versa. It is valid only during the current request.
The following example demonstrates how to transfer data from
controller to view using ViewData.

Example: ViewData in Action method


public ActionResult Index()
{
IList<Student> studentList = new List<Student>();
studentList.Add(new Student(){ StudentName = "Bill" });
studentList.Add(new Student(){ StudentName = "Steve" });
studentList.Add(new Student(){ StudentName = "Ram" });

ViewData["students"] = studentList;

return View();
}
In the above example, we have added a student list with the key
"students" in the ViewData dictionary. So now, the student list can
be accessed in a view as shown below.

Example: Access ViewData in a Razor View


<ul>
@foreach (var std in ViewData["students"] as IList<Student>)
{
<li>
@std.StudentName
</li>
}
</ul>
Please notice that we must cast ViewData values to the appropriate
data type.

You can also add a KeyValuePair into ViewData as shown below.

Example: Add KeyValuePair in ViewData


public ActionResult Index()
{
ViewData.Add("Id", 1);
ViewData.Add(new KeyValuePair<string, object>("Name", "Bill"));
ViewData.Add(new KeyValuePair<string, object>("Age", 20));

return View();
}
ViewData and ViewBag both use the same dictionary internally. So
you cannot have ViewData Key matches with the property name of
ViewBag, otherwise it will throw a runtime exception.

Example: ViewBag and ViewData


public ActionResult Index()
{
ViewBag.Id = 1;

ViewData.Add("Id", 1); // throw runtime exception as it already has


"Id" key
ViewData.Add(new KeyValuePair<string, object>("Name", "Bill"));
ViewData.Add(new KeyValuePair<string, object>("Age", 20));

return View();
}

Example to pass object data using viewdata

Take this product model


namespace MvcPassDataToView.Models
{
public class Product
{
public long Id { get; set; }

public string Name { get; set; }

public string Description { get; set; }

public decimal price { get; set; }


}
}

In the Index action of your controller create a Product object and assign it to a
ViewData dictionary object as follows.

1
2 public ActionResult Index()
3 {
Product cap = new Product
4 {
5 Id = 1,
6 Name = "Golf cap",
7 Description = "A nice cap to play golf",
price = 10m
8 };
9
10 ViewData["MyProduct"] = cap;
11
12 return View();
13 }
14

Change the Index View file contents as follows, build and run your application.
@using MvcPassDataToView.Models
1
@{
2 ViewBag.Title = "Index";

}
3

4
<h2>Index</h2>
5

6
@{
7
var prod = (Product)ViewData["MyProduct"];
8
}
9

10
<h1>Product</h1>
11
<h3>ID: @prod.Id</h3>
12 <h3>Name: @prod.Name </h3>

13 <h3>Description: @prod.Description</h3>

14 <h3>Price: @prod.price</h3>

In browser its look like this output

Points to Remember :
1. ViewData transfers data from the Controller to View, not vice-versa.
2. ViewData is derived from ViewDataDictionary which is a dictionary
type.
3. ViewData's life only lasts during current http request. ViewData
values will be cleared if redirection occurs.
4. ViewData value must be type cast before use.

TempData
1. TempData is derived from the TempDataDictionary class and is
basically a Dictionary object i.e. Keys and Values where Keys are
String while Values will be objects.
2. Data is stored as Object in TempData.
3. While retrieving, the data it needs to be Type Casted to its
original type as the data is stored as objects and it also requires
NULL checks while retrieving.
4. TempData can be used for passing value from Controller to
View and also from Controller to Controller.
5. TempData is available for Current and Subsequent Requests. It
will not be destroyed on redirection.

Example
In the below example, a string value is set in the TempData object
in Controller and it is redirected to another Controller and finally it
is displayed in View.
First Controller
public class FirstController : Controller
{
// GET: First
public ActionResult Index()
{
TempData["Message"] = "Hello MVC!";
return new RedirectResult(@"~\Second\");
}
}

Second Controller
public class SecondController : Controller
{
// GET: Second
public ActionResult Index()
{
return View();
}
}

View of Second Controller


<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
</head>
<body>
<div>
@TempData["Message"];
</div>
</body>
</html>

You might also like