1

I'm building my first MVC project and I have a question about the model.

Each webpage can only contain 1 model, yet my page will require 2 models, one is the search option (the ability to narrow your search such as selecting price range, colour etc) as well as the data.

Is it really as simple as creating a new Model, similar to a ViewModel which in this case would only have 2 properties, a SearchModel and a ProductModel?

tereško
  • 58,060
  • 25
  • 98
  • 150
Dave
  • 8,163
  • 11
  • 67
  • 103

2 Answers2

1

Yes, there are really two "models" which is sometimes confusing. There's the "View Model" and the "Domain Model." The view model is passed directly to and from the view. The domain model describes the real-life domain that you're dealing with and is what the database persists. Often, they are the same thing, such as if you're displaying information for a single real domain object (e.g., a car). If you have two domain models that go on one page, you should make a view model with both as properties.

Hut8
  • 6,080
  • 4
  • 42
  • 59
  • Perfect, so many pennies are dropping! This is great, thank you very much for the help. – Dave Feb 15 '13 at 12:55
1

If you are looking to have two models in a view then this question might provide useful information:

multiple-models-in-a-view

Edit:

A good example is the 'Manage' view in the default 'Account' controller of a fresh mvc app. It uses a partial view to handle the changing of a user's password. Whilst both views are using the same model type it shows how to implement a partial view. In this case both the main view and the partial are submitting to the same method on the controller, hence they need to use the same model (which is a parameter for the controller method). But if the partial were to invoke a different controller method then the submitted model could be different. Hope this makes sense :)

Community
  • 1
  • 1
Whiplash450
  • 943
  • 2
  • 12
  • 22
  • The post you cited has left me confused; I thought that each page can only have 1 model, yet the answer seems to suggest you can have multiple models by using partial views. Is that correct? – Dave Feb 15 '13 at 12:56
  • Yes a partial view can have its own model. Calling a partial view doesn't reload the main page so you can do stuff inside of a page without refreshing/submitting the main page. – Whiplash450 Feb 15 '13 at 14:17