I'm trying to make an application in ASP.NET MVC. I'm using AutoMapper for the conversion between entities and ViewModels.
In most cases, this works fine, but when I need to add some additional data (f.e. a list of items for a drop-down list), I'm a bit confused about where I should retrieve this data and populate the ViewModel with it (should I do this in the Service-layer/Controller-layer)?
Here is my code:
Entities
class Book
{
public int Id { get; set; }
public string Title { get; set; }
public string ISBN13 { get; set; }
public Genre Genre { get; set; }
}
class Genre
{
public int Id { get; set; }
public string Name { get; set; }
}
ViewModels
class EditBookViewModel
{
public int Id { get; set; }
public string Title { get; set; }
public string ISBN13 { get; set; }
public int GenreId { get; set; }
public IEnumerable<Genre> AllGenres { get; set; }
}
Service-layer
class BookService
{
public EditBookViewModel GetBookForEdit(int id)
{
Book book = _context.Books.Find(id);
EditBookViewModel vm = _mapper.Map<EditBookViewModel>(book);
vm.AllGenres = _context.Genres.ToList(); //in Service-layer, or Controller?
return vm;
}
}
Is this the right place to create and fill-in the ViewModel? Or should I do this in the Controller-layer?
Thank you in advance!
1 Answer 1
If your app is going to have a Service Layer and Controllers, then it does not make sense for the service layer to be responsible for composing ViewModels, which are intended to be the interface between a View and a Controller.
The service layer should be something that is view-agnostic. If another use for the "GetBook" method is needed, it will be polluted with view-specific details.
Your Service Layer should manipulate and return Entities. Your controller should map those into a ViewModel.
Explore related questions
See similar questions with these tags.