MVC - Sharing ViewModel instances across multiple Views

404 views Asked by At

Just wondering what peoples thoughts are about sharing the one view model instances across multiple Views?

Is this an anti pattern or is it accepted practice, what are the pros and cons?

1

There are 1 answers

0
danielfishr On

Just from my experience

The main drawback can be refactoring effort in future if the views diverge in what they display. You need to think about how likely this is when you make the decision to share the view.

Also be careful with the naming of the view models. For example if you have the views Book/Edit.aspx and Book/Add.aspx you would not want AddBookViewModel.cs used in the Book/Edit.aspx. This could create some confusing looking code in the your tests for example.

In the above example, I would typically go with CreateEditBookViewModel.cs

If you look at the likes of SharpArchitecture (www.sharparchitecture.net/) I believe they use this approach in their scaffolding and they also share the elements of the views using the shared viewmodels via partials.

In terms of it being an anti-pattern, I'd say no; just healthy code reuse.