ViewBag - (ASP.NET MVC)
In ASP.NET MVC, ViewBag is a dynamic object that is used to share data between a controller and a view. The ViewBag object is a dynamic object that can be used to store and retrieve values that are used in a view.
Syntax
The syntax for adding values to the ViewBag object is straightforward. Simply assign a value to a property of the ViewBag object within the controller, and then retrieve the value from the ViewBag object within the view:
In the Controller:
ViewBag.Name = "John";
ViewBag.Age = 30;
In the View:
<p>My name is @ViewBag.Name, and I'm @ViewBag.Age years old.</p>
Example
Here is an example of how to use the ViewBag object in an ASP.NET MVC application:
public ActionResult Example()
{
ViewBag.Name = "John";
ViewBag.Age = 30;
return View();
}
<!-- View code -->
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Example</title>
</head>
<body>
<p>My name is @ViewBag.Name, and I'm @ViewBag.Age years old.</p>
</body>
</html>
Output
The output of the above example will be:
My name is John, and I'm 30 years old.
Explanation
The ViewBag object is a dynamic object that is used to share data between a controller and a view. It is particularly useful when you only need to share a small amount of data between a controller and a view. You can assign any type of object to a ViewBag property, and then retrieve the value of that property in the view.
Use
ViewBag can be used to pass data from a controller to a view. It is useful when you only need to pass a small amount of data.
Important Points
Here are a few important points to keep in mind when using ViewBag in your ASP.NET MVC applications:
- The
ViewBagobject is a dynamic object, which means that you can assign any type of value to it. - The
ViewBagobject is not strongly typed, which means that you are responsible for ensuring that you are using the correct property name. - Values that are added to the
ViewBagobject are not persisted across HTTP requests.
Summary
In this page, we discussed ViewBag, a dynamic object that is used to share data between a controller and a view in an ASP.NET MVC application. We covered the syntax, example, output, explanation, use, important points, and summary of the ViewBag object. By using ViewBag, you can easily pass data from a controller to a view in an ASP.NET MVC application.