views:

160

answers:

1

For ViewData, rather than using strings as the key, I'm using enums. I currently have one big list right now that can be accessed from anywhere. Some enums are used across multiple Controller/View pairs. Is there a better way to categorize these enums rather than just an ever growing list?

I don't like the hard coded strings that are common for ViewData. Enums give great intellisense. I thought about categorizing enums by controller. That doesn't work so well though since particular enum values might be shared across controllers and need some centralized location.

+2  A: 

Instead of using the ViewData dictionary, have you considered using strongly typed ViewModels?

If you have a class called MyViewModel, you can do this from your Controller class:

public ViewResult Index()
{
    return this.View(new MyViewModel());
}

MyViewModel can be any class - it does not need to implement any specific interfaces or anything. You can then add all the properties to that class that you need in the View.

You can define the view as a strongly typed View based on your ViewModel. In your .aspx file, you need to replace this:

Inherits="System.Web.Mvc.ViewPage"

with this:

Inherits="System.Web.Mvc.ViewPage<MyViewModel>"

This means that you will now have strongly typed access (including IntelliSense) to the ViewModel from the View:

this.ViewData.Model.MyProperty

I never use the ViewData dictionary, as the alternative outlined here is much stronger.

Mark Seemann
Right but that doesn't work if my controller accesses 2+ model classes to get certain values. The View can be typed as only one class. ViewData lets me takes several values from several classes and send them to the View, which doesn't do anything but display the values.
4thSpace
The ViewModel should support the View, so it can have whatever properties you need it to have, and be as complex as you want it. Where the data comes from is irrelevant - that is the responsibility of the Controller. Each ViewModel can be tailored to a specific View, so you can give it exactly the data it needs to have. If you want to send complex data to the View, just create a new ViewModel that has these complex classes as individual properties. There really is no need to use the ViewData dictionary.
Mark Seemann