Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
ViewBag Property

ControllerBase.ViewBag Property

 

Gets the dynamic view data dictionary.

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

No code example is currently available or this language may not be supported.

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")
Return to top
Show:
© 2015 Microsoft