I'm attempting to learn ASP.NET MVC and I've come across some code at our company that uses ViewBag. I've looked into what it is and it just appears to be a container for variables that can be declared in the controller and then accessed from the view.
I've used other frameworks like Ruby on Rails and Struts that don't make me do this. In ruby on rails in particular, I can just call get the variable easily in the view by doing:
<%= variable %>
Further research has led me to believe that using ViewData and ViewBag are not encouraged. Can someone explain the use of it over just getting the variable directly from the controller?
Thanks.
In ASP.NET MVC you have to explicitly pass the data the view needs from the controller to the view.
The encouraged way of doing this is to use a strongly typed view and pass the data in form of a class instance:
public ActionResult MyAction() {
return View(new MyViewModel { Prop1 = "Value1", ... });
}
In your view you specify the model class the view uses:
@model MyViewModel
The ViewData and ViewBag are alternate / historical ways of passing data to the view. ViewData is a dictionary and requires type casting to get values out of it. ViewBag is a dynamic object. Both lack the benefits you got from strongly typing your Views.
ViewData has some other properties to access the models metadata or modelstate. See ViewData.ModelMetadata
for example.
Can someone explain the use of it over just getting the variable directly from the controller?
Yes, decoupling. The MVC pattern states, that the View has no dependency on the controller. When your view can access properties of the controller it would be coupled to that specific controller and the M in MVC has disappeared.