Introduction
The MVC is an application development pattern or design pattern which separates an application into three main components:-
1) Model: A Model is a part of an application that implements the logic for the application's data domain.
2) View: View is a component used to form the application's user interface. It is used to create web pages for the application.
3) Controller: Controller is the component that controls the user interaction. It works along with the model and selects the view to render the web page.
ASP.NET MVC provides three essential variables to store and pass values from controller to view. The ViewData and ViewBag are similar except TempData, with some additional features.
Let's learn about these variables one by one.
ASP.NET MVC ViewBag
MVC ViewBag is a dynamic property introduced in .Net Framework version 4.0. it is used to send data from the controller to the view page. ViewBag can get and set values dynamically; that's why it is called dynamic property. It does not require type conversion and converts type dynamically.
Example:
Let's implement the ViewBag property to understand it properly. The controller and an Index file are given below.
Controller
using System;
using System.Collections.Generic;
using System.Web.Mvc;
namespace ViewBagExample.Controllers
{
public class ViewBagController : Controller
{
// GET: ViewBag
public ActionResult Index()
{
List<string> Courses = new List<string>();
Courses.Add("Computer Networks");
Courses.Add("Operating System");
Courses.Add("DBMS");
Courses.Add("Compiler Design");
ViewBag.Courses = Courses;
return View();
}
}
}
View
<!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>