Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - ViewModels For Edit

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.

like image 672
CocoB Avatar asked May 18 '10 15:05

CocoB


2 Answers

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.

like image 180
Paul Mendoza Avatar answered Oct 07 '22 20:10

Paul Mendoza


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.

like image 37
Ryan Avatar answered Oct 07 '22 21:10

Ryan