I have an ASP.NET MVC 3 application.
I have a Model, ViewModel, View, Controller.
I use Ninject as IoC.
My Controller uses a ViewModel to pass data to the View.
I've started to use Services (concrete and interface types) to take information from the ViewModel and query it against the database to manipulate it.
Can I use the same Service to setup the ViewModel? Or is this going against the grain of the design pattern?
I.e. Can I abstract setting up the ViewModel in the Service layer?
Scenario
The scenario is; my Model has lots of references to other Models, so when I setup the ViewModel in the controller it's to verbose, and I feel the Controller is doing too much. So I want to be able to just do something like:
var vm = _serviceProvider.SetupViewModel(Guid model1Id, Guid model2Id, /*etc..*/)
And the SetupViewModel function in the ServiceProvider would look like this:
public MyModelViewModel SetupViewModel(Guid model1Id, Guid model2Id, /*etc...*/)
{
var vm = new MyModelViewModel();
var model1 = _repository.Model1s.FirstOrDefault(x => x.Id.Equals(model1Id));
var model2 = _repository.Model2s.FirstOrDefault(x => x.Id.Equals(model2Id));
// etc....
vm.Model1 = model1;
vm.Model2 = model2;
return vm;
}
By doing this I could also add some null conditions as well, not worrying about making my Controller really really really big!!
I use 1 ViewModel for the Create/Edit actions. I don't reuse the ViewModel elsewhere.