Skip to main content

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Visit Stack Exchange
Asked
Viewed 2k times
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!

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.

Your Answer

Reminder: Answers generated by AI tools are not allowed due to Software Engineering Stack Exchange's artificial intelligence policy

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.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.