Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

Both ViewBag and ViewData are meant to maintain the View/Controller decoupling. Data that normally would fit in a ViewModel could be placed in the ViewBag or the ViewData to be used by the view. Data like selection list data, that isn't necessarily specific to the view, for example.

The difference between the ViewBag and the ViewData is that the view data is accessed as a key/value container (a dictionary) where data in the ViewBag is accesses via properties (it's a dynamic object, so assigning a new value to a "property" creates the property).

Update:

When you use <%= variable %> you're accessing a variable right on the specific view. In order for the controller to set this value, it must be coupled to the view and assign it directly. this is, of course, possible, but introduces coupling directly to the view that you might not want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top