Header background image for AlwaysMoveForward.com
Software

My MVC Experiment Part 7 - Fun with ViewData

By Arthur Correa • Author

Okay so I'm actually going into my MVC details now.

When I first started using ASP.Net MVC I dumped everything into the ViewData dictionary using ViewData[""].  I had noticed the ModelContainer class that is created for you when you first create an MVC project, but honestly why bother?  You can just dump whatever you want into the ViewData at will so why create a bunch of properties on a class?

Uhm ok, but lets take the opposite approach.  Why NOT create a bunch of properties on the class.  My opinion was that you'd very frequently have a lot of properties that were on the ModelContainer that weren't used all the time.  As a result a ModelContainer interface that was clutttered with junk whenever you used it.  Sure if you had stuff that was used all the time then it might make sense, but I hadn't yet come across enough commonalities in my code to justify it.

So I went on my merry way.  I liked using ViewData[""], but I found it a pain in the view because it wasn't strongly typed.  Having to do "as" all over the place, or use the CodeBehind file to get the dictionary element and return it as strongly typed to the .aspx file was ok, but not ideal.

Then at some point I found out that you could add a template type to your view class.  Hmm so that's why you can pass the model object back as a parameter to your View!  So I started playing around with having Model classes that mirroed my Controllers. (I.ei I have a UserController and a UserModel).  At this point using a strongly typed model made some more sense because.

  1. I had found enough commonality in my ViewData elements that I could imagine a need for a common Model base class.
  2. I was getting sick of dealing wtih "as" and code behind files.
  3. I wanted to try it to see if I would like it any better. (not a great reason, but remember this blog site is a learning experience more than anything else).

So I created a base Model class and derived from it to create a Model for each Controller.  I have to say I like having the strongly typeed objects ready to use in my View classes.  That being said I do find that for almost every View there is a Model element that isn't being used and is just wasted space.

Is that a huge deal?  No not really, I could go all out and create a different Model for each View if I really wanted to deal with that.  It may structurally and organizationally be kind of nice to do that actually, but it feels like a lot of busy work for not a lot of gain. 

I'm really curious to hear how others are using ViewData.