In this article I will explain a short tutorial with example on how to use ViewBag in ASP.Net MVC.
ViewBag is a wrapper written over ViewData in order to make it easier to use.
What is ViewBag
1. ViewBag is a Wrapper built around ViewData.
2. ViewBag 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 is used for passing value from Controller to View.
5. ViewBag is available only for Current Request. It will be destroyed on redirection.
Example
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
{
// GET: Home
public ActionResult Index()
{
ViewBag.Message = "Hello MVC!";
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>
<div>
@ViewBag.Message
</div>
</body>
</html>
Screenshot
Downloads