Total: $0.00
Taxes and shipping calculated at checkout
ViewBag is an object which is dynamically passing the data from Controller to View and this will pass the data as the property of object ViewBag. We do not need to typecast to read the data for null checking here.
Controller:
1
2
3
4
5
|
Public ActionResult Index()
{
ViewBag.Title = “Hello”;
return View();
}
|
View:
1
|
<h2>@ViewBag.Title</h2>
|
Here is an example:
Controller:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
using System;
using System.Collections.Generic;
using System.Web.Mvc;
namespace ViewBagExample.Controllers
{
public class ViewBagController : Controller
{
public ActionResult Index()
{
List<string> Courses = new List<string>();
Courses.Add("J2SE");
Courses.Add("J2EE");
Courses.Add("Spring");
Courses.Add("Hibernates");
ViewBag.Courses = Courses;
return View();
}
}
}
|
View:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<h2>List of Courses</h2>
<ul>
@{
foreach (var Courses in ViewBag.Courses)
{
<li> @Courses</li>
}
}
</ul>
</body>
</html>
|