You only get 1 type for Model
. There is no changing that. The correct solution is to create a model that contains the data the view needs. That is the very essences of MVC. This is not where OOP design comes in. Creating models that are shared across views or use inheritance is an OOP. A view shouldn't know or care about the underlying data structure. All it wants is the data and that should ideally be as flat as possible. So aggregation is the best choice here. Create a MyViewModel
that contains the 2 models you want the view to use. It is simple, it solves the problem and it has no impact on any other areas of the code.
public class UsersAndCompany
{
public User User { get; set; }
public Company Company { get; set; }
}
Then your view can use either subset of data to build its UI. Other views can use one or the other or both as they see fit as well. Note that if there is a relationship between User
and Company
then you should ideally relate the models together anyway. Be careful about trying to use the database structure as the representation that the view uses. If you do that then you end up with a view that changes when the database changes. The view should get all the data it needs in a simple format irrelevant of how it is stored in the backend.
In special cases where you need to pass extra data to a view (such as lookup values or whatnot) you can also use ViewBag
to store data. But this should be reserved for data that sits outside the "model" that is being displayed. It makes the view harder to use and won't survive roundtrips to the server.
Yet another option is to have your Razor code make a call to your backend service and store that into a temp variable. That code runs in the context of the view and therefore can get data that the view needs. This also is not recommended because it makes the view harder to use and it doesn't work with DI. But in a pinch it could be done.