I wonder, why everybody hates ViewData so much?
I find it quite useful and convenient. I tell you why: typically every controller action has it’s own ViewModel, so it’s used only once and I find it very tedious to modify ViewData class every time I need to add extra portion of data to view (adding extra field to class usually leads to modifying its constructor). Instead I can write in controller
ViewData["label"] = someValue;
// in mvc 3 even better:
ViewData.Label = someValue
and in view
<%= ViewData["label"] %>
<%-- mvc 3: --%>
<%= ViewData.Label %>
or for complex types:
<% ComplexType t = (ComplexType)ViewData["label"]; %> // and use all benefits of strong typing
<%= t.SomeProperty %>
Writing a controller action I do not have to switch to another class, when I need to add some data to view.
And a big plus for me: no flooding your project with senseless classes and switching between them and others.
I agree that usage of “magic strings” could lead errors which are not caught by compiler, but these errors localized in very small part of code and can be discovered very quickly. Besides, how do you think guys working with dynamic languages (rails, django) lives without strong typing at all?)
What’s your opinion about using ViewData?
I think this goes beyond just the magic string argument. I would argue that ViewModels are a good thing and not senseless classes because they help keep the Views cleaner and easier to read than accessing ViewData all over the Views.
When you get to five, ten, twenty pieces of data that need to be displayed in a view are you really going to pass all that data over as ViewData? It will make your view harder to follow and that data won’t have any meaning. Making a ViewModel and strongly typing the view to that ViewModel will not only make the code easier to read, but you don’t have to go casting ViewData objects all over your code.
I do think ViewData is good for certain cases, but when you are dealing with a lot of data it can easily be abused in my opinion.