csharp

ViewBag In Asp.Net MVC C#

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:

  • It enables you to send values dynamically between the controller and view in ViewBag In Asp.Net MVC
  • ViewBag Contain any random data and it is not strongly typed
  • ViewBag is wrapper around ViewData.
  • ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
  • The ViewBag’s life only lasts during the current http request. ViewBag values will be null if redirection occurs.
  • When It Is Used.

  • ViewBag In Asp.Net MVC used when you want to share data dynamically.
  • We can use ViewBag objects for small amounts of data, transferring it from the controller to the view.
  • If you want to assign any number of propertes and values to ViewBag
  • Leave a Reply

    Your email address will not be published.