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 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.
 
 
ViewBag Example
In the below example, a string value is set in the ViewBag object in Controller and it is then displayed in View.
Controller
public class FirstController : Controller
{
    // GET: First
    public ActionResult Index()
    {
        ViewBag.Message = "Hello MVC!";
        return View();
    }
}
 
View
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <div>
        @ViewBag.Message
    </div>
</body>
</html>
 
 
Screenshot
ASP.Net MVC: ViewBag Tutorial with example
 
 
Downloads