In this article learn about ViewBag In Asp.Net MVC C#.
ViewBag:
ViewBag is one type of dynamic object and is generally used for passing data to a view. It is not recommended for passing several pieces of data into a view because of its dynamic nature.
ViewBag Can be useful for transferring temporary data from a controller to View. It is a base class of all controllers.ViewBag is not strongly typed, meaning that it can contain any random data.
This example explains how to send data from a controller to View using ViewBag In Asp.Net MVC. This example shows the total name of the employee.
[php]
//Write this code on your Controller Class
public ActionResult Index()
{
ViewBag.EmployeeName = new List<string>()
{
"Mark",
"Gordan",
"Peter",
"Flintoff",
"Smith"
};
return View();
}
[/php]
Put this code on Index.cshtml
[php]
@{
ViewBag.Title = "Employee List";
}
<h2>Employee List</h2>
<div style="font-family:Arial">
<ul>
@foreach (string employeeName in ViewBag.EmployeeName)
{
<li style="color:blue">
@employeeName
</li>
}
</ul>
</div>
[/php]
Screenshot Show the output after run the project.
Key Point:
When It Is Used.