Reputation: 121
Bit of confusion, which I'm sure can easily be cleared up :).
Lets say we have a table called "Contacts". The "Index" view for this table would be a datatable, listing all contacts in the table with First name, email and phone. Now, this would have a viewmodel containing Firstname, email and phone.
Next we would need a details page, which will have the details for each contact in full, IE, fullname, first or second contacts, other phone numbers, website address and notes etc. Should this be a second Viewmodel?
Then we'd have a create page, which had have all the fields to be filled in. Would this be another viewmodel?
Finally, would this all go into the same class file or separate files?
Thanks
Upvotes: 0
Views: 556
Reputation: 1
No need to create a more than one view model for a view. First you should create a models for your database tables(contact, contact details, etc..). Later based on your view requirement you can create a view model using models. Even model can be directly used as a view model if requires.
Better to create a separate view model for a view. it is useful to combine a data from multiple models and also you can have a calculated properties and methods.
Upvotes: 0
Reputation: 61
So you can have Model and multiple ViewModels.It is best to keep every ViewModel in a different file. If you use same Models as your ViewModels, your application should be very small and simple and should contain only CRUD operations. But if you are building large or enterprise applications with large teams (with two or probably more developers), you should have concepts like Dependency Injection, Services, Repositories, Façades, Units of Work, Data Access Objects etc.
To simplify your mapping needs between Models and ViewModels, you can use AutoMapper https://github.com/AutoMapper/AutoMapper
or install with nuget Install-Package AutoMapper
Upvotes: 2
Reputation: 27962
Short answer: Yes.
Long answer: Yes, it seems logical in your specific case. View/edit models often differ, too - in datatypes, sets of data included, fields editable vs. viewable. On the other hand, with modern browser-based frontends less specialized view models may lead to looser coupling between backend API and frontend, making UI changes easier.
Code organization is a subjective matter.
Upvotes: 1
Reputation: 3394
As usual the answer is ain't common, it depends on how you really want to implement it. But for the sake of patterns and organized code, i would recommend that you have:
Upvotes: 3