ViewBag in MVC ASP.NET
Is a DynamicViewData object, it is a ViewData wrapper class to allow flexible access to the object. ViewBag also allows us to use dynamic properties (using dots instead of square brackets like ViewData). Using ViewBag is similar to ViewData but more convenient because it doesn't require casting.
The following example demonstrates how to pass data from controller to view using ViewBag.
namespace MVC_BasicTutorials.Controllers
{
public class StudentController : Controller
{
IList studentList = new List() {
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 ActionResultIndex()
{
ViewBag.TotalStudents = studentList.Count();
return View();
}
}
}
In the above example, we want to display the total number of students in the view. So assigned the number of students using ViewBag.TotalStudents = studentList.Count().
Now, in the Index.cshtml view, you can access the ViewBag.TotalStudents property and display the total number of students as shown below.
@ViewBag.TotalStudents
Result:
Total Students: 5
ViewBag does not require casting while retrieving values.
ViewBag is a wrapper class around ViewData. It will throw a runtime exception, if the ViewBag property name matches the key of ViewData.
Did you find this article helpful?
Support the author so they can write more quality articles!
Points to remember :