Is it generally a good practice to have both view and edit models for an MVC app? Meaning, I wouldn't want validation attributes on a view model since it's basically read-only.
I generally create a new view model for each view. I find that the reuse in practice of ViewModels is just very low and trying to make them super generic doesn't work great and leads to some weird cases.
When I first started creating ViewModels I'd create these really abstract ViewModels that I'd try to enforce a bunch of business logic into but then I realized that in most cases the data I was trying to show in each case was totally different and reuse wasn't working. So I just started breaking my ViewModels into really tiny pieces that are used once. So far this has worked well.
Most of my business logic I now try to keep in the model instead of the view model. I my case my model is a entity framework model and I put the business logic in partial classes hanging off of my DB objects.
If your views are CRUD views, using the same view model makes sense. On the read only view, validation attributes would be ignored since you're not inputting a form. Once you get away from CRUD you have a lot more variations in how to structure your VMs. I have some situations where a field can only be set during insert. In this case I use the same VM for rendering the add, readonly and update screens (with DisplayFor vs InputFor in the view html itself), but I have different input models on my Insert and Update action methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With