Pass Data from Controller to View using ViewBag in MVC
In my last article I explain how to send data from view to controller using ViewData. In this article we will discuss how we can send data using ViewBag. ViewBag used dynamic property which introduced in C# 4.0 and it is typed object which decide type at runtime. This is the reason we didn't get compile time error.
It is actually maintain a dynamic ViewData Dictionary internally so you can say that it’s a wrapper around ViewData.
Create a controller name Home and create view name Index.
In this view create a list of type string in which stores the Department Name.
public class HomeController : Controller
public ActionResult Index()
List<string> dept = new List<string>()
ViewBag.dept_name = dept;
In this example we create dynamic property named dept_name.
Now use this ViewBag in View
Layout = null;
<meta name="viewport" content="width=device-width" />
Employee Departments are:-<br />
@foreach (string dept in ViewBag.dept_name)
As you can see that we need not to perform the type casting while working with ViewBag.
The output of this code is as follows:-
for any query send mail at email@example.com