In this article I will explain with an example, how to pass (send) data from
Controller to
View using
ViewBag in
ASP.Net MVC Razor.
This article will illustrate how to create a
ViewBag object, store some data and then access the
ViewBag object inside the
View using Razor syntax in
ASP.Net MVC Razor.
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.
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