Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using two strongly typed models for one MVC view

Am I missing something fundamental to the principals of MVC or am I going mad?

If I have a view that displays a list of books and a list of authors, I have to create class that would have the list of Books and list of authors as properties. Right?

I would then strongly type the view to use this class.

Now I want to create a new page with the same listings but that also has a list of promotions. Do I need to create another class with a list of Books property, a list of authors property and a list of promotions property?

If I am creating classes for all the views I am creating a hell of a lot of extra work. Am I supposed to be creating strong typed partials for each of these? What if the layout differs each time?

Currently I have a BaseViewData class that is used by all the views as it contains some common properties. However, I am now struggling to get other items in without completely bloating the BaseViewData class.

Please can someone help me understand the theory that all the simple examples don't cover.

like image 632
William Hurst Avatar asked Oct 15 '22 16:10

William Hurst


2 Answers

I use the ViewData extension methods from MvcContrib that add support for multiple strongly typed models (as long as they are different types). Code to add them to the ViewData looks like this:

User currentUser = GetCurrentUser();
List<Project> projectList = projectRepository.GetRecentProjects(currentUser);
ViewData.Add(user);
ViewData.Add(projectList);

Code in the view to pull them out looks like this:

User user = ViewData.Get<User>();
List<Project> projectList = ViewData.Get<List<Project>>();

This removes both the "magic strings" and the type casting. Note, this doesn't do anything with Model property of the view.

like image 187
Erv Walter Avatar answered Oct 20 '22 16:10

Erv Walter


Create ONE container class for ever object in your system, and use for all views - simple

Objects with null value have no real overhead

like image 33
TFD Avatar answered Oct 20 '22 15:10

TFD