There seem to be multiple means of passing model data from controllers in asp.net mvc to views. Its not clear to me if there’s a recommended approach in the mvc v1 and v2 releases or if like most things in life, it depends. I’ve seen several approaches:
Option 1 – Populate the controller’s ViewData dixtionary in either an icky string-based indexing way with casting in the view, or the in a strongly typed way by creating a strongly typed custom model class and passing that via ViewData.
Option 2 – Use ViewData.Model, which I’m not sure I even understand.
Option 3 – Use ViewPage.Model, in which case I’m not sure how you pass the model data from the controller.
I’ve seen a number of posts poo-pooing options 1 and 2 but I don’t understand why. These posts seem to highly recommend 3 in most cases.
How do you approach this? Is there a standard way?
Every view ‘should’ have a specific model. This is sometimes more work so people use short cuts like
ViewData, which works but is just not as clean and type safe in my opinion, so I prefer to have everything in the view’s model.You can then make all your views stongly typed. This is a very clean way to do so. Then in your controller you just call the view like:
Then in your views you can access all the data via
ViewPageModeland it is all type safe and enforced from the controller as well.EDIT from comments:
You don’t need to use
ViewDataat all if you don’t want. You can encapsulate all the data your view needs in a model. Just like the example you quoted withProductsListViewData. It’s just a model that contains all the items that were going to be stored in theViewData. Both ways work but when you encapsulate it in a class (preferred method where everything is in the model) then all the bits and pieces are strongly typed.ViewDatais a generic container so even though you can just put anything you want into it, it is not type safe and therefore not as ‘clean’. It comes down to preference and maintainability. There is only option 1 and 3. Your option 2 is misunderstood and is just option 3 in reality. There is noViewData.ModeljustViewPage.Model.