Export (0) Print
Expand All

ControllerBase.ViewBag Property

Gets the dynamic view data dictionary.

Namespace:  System.Web.Mvc
Assembly:  System.Web.Mvc (in System.Web.Mvc.dll)

function get ViewBag () : Object

Property Value

Type: System.Object
The dynamic view data dictionary.

The ViewBag property enables you to dynamically share values from the controller to the view. It is a dynamic object which means it has no pre-defined properties. You define the properties you want the ViewBag to have by simply adding them to the property. In the view, you retrieve those values by using same name for the property.

The following example shows how to create two properties for the ViewBag in a controller.

public ActionResult Index()
{
    ViewBag.MyMessageToUsers = "Hello from me.";
    ViewBag.AnswerText = "Your answer goes here.";

    return View();
}

The next example shows how to retrieve those ViewBag properties from your view. The first line displays the value of the MyMessageToUsers property as text. The second line creates a text box and pre-populates it with the value of the AnswerText property.

@ViewBag.MyMessageToUsers
@Html.TextBox("AnswerText")
Show:
© 2014 Microsoft