In this article I will explain a short tutorial with example on how to use ViewBag object in ASP.Net Core.
ViewBag object is a wrapper written over ViewData object in order to make it easier to use and it was present in ASP.Net MVC and now continued in ASP.Net Core MVC.
What is ViewBag
1. ViewBag is a Wrapper built around ViewData object.
2. ViewBag object is a dynamic property and it makes use of the C# 4.0 dynamic features.
3. While retrieving, there is no need for Type Casting of data.
4. ViewBag object is used for passing value from Controller to View.
5. ViewBag object is available only for Current Request. It will be destroyed on redirection.
Controller
The Controller consists of following Action method.
Action method for handling GET operation
Inside this Action method, a string value is set in the ViewBag object and simply the View is returned.
public class HomeController : Controller
{
public IActionResult Index()
{
ViewBag.Message = "This is my First MVC Core App.";
return View();
}
}
View
Inside the View, simply the ViewBag object is used to display the Message.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@ViewBag.Message
</body>
</html>
Screenshot
Downloads