1

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!

asked Nov 2, 2022 at 20:38
0

1 Answer 1

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.

answered Nov 3, 2022 at 15:42

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.