My view model looks something like this:
public class CarViewModel {
public CarModel Car { get; set; }
public List<CarModel> Cars { get; set; }
}
CarModel looks like:
public class Car() {
public string Make { get; set; }
public string Model { get; set; }
. . .
}
My goal is to only have a single view model that I can use for both my list views and single views. For the list view, I would hydrate the Cars list and use that within the view, while ignoring the single Car entity.
For a details view, it would be the opposite. My controller would hydrate the single Car entity, and the view would use that and ignore the List.
This is partially working, but the model binding is weak.
DRY (don’t repeat yourself) and SOC/SRP (separation of concerns/single responsibility principal) seem to be conflicting here. What’s the best way to handle both a list view plus a details view? I have a feeling the answer is to create duplicate view models, but I don’t want to duplicate code if I can help it.
It seems you are over thinking this a little bit. Simply have one class called CarViewModel, which would look like this:
For your Detail/Edit/Create views, your view would be of type
CarViewModel. For your list view, simply pass a list ofCarViewModelto the view. Make the model type on the list viewIEnumerable<CarViewModel>(). This removes a class from your current suggested path forward and keeps a single View Model responsible for all things Car related.EDIT
The concern is – “What if my list view model needs more information than just a list of Cars”. In this case, it would make sense to create a stand alone view model for the list view as it requires additional information.
Note that we are not repeating ourselves as we are still passing a list of cars to the view. However, since we need more than the list of cars, this view model needs to have more properties than just a list. There is nothing wrong with having multiple view models if your code/views require that information.