Home > OS >  Where do you store the ViewModel in MVC using .NET Core?
Where do you store the ViewModel in MVC using .NET Core?

Time:10-04

I'm currently storing my ViewModels as private methods in the HomeController (called by the Index()), however the size is exceeding 300 lines now.

Where should one store the ViewModel?

And to minimize the ViewModel, is it allowed to the ViewModel with a Constructor which will map some of the objects (for example to create an empty List) or pass the Model for mapping instead of doing it in the Controller?

        [HttpPost]
        public IActionResult Index(List<SomeType1> SomeType1)
        {
            var viewModel = MapMainViewModel(SomeType1);

            return View(viewModel);
        }

        private MainViewModel MapMainViewModel(List<SomeType1> someType1)
        {
            return new MainViewModel()
            {
                SomeModel = new SomeModel()
                {
                    SomeType1 = MapSomeType1(),
                    SomeOtherType2 = new List<SomeType1>()
                }
            };
        }

        private List<SomeType1> MapSomeType1()
        {
            var result = new List<SomeType1>()
            {
                ...
            };

            return result;
        }

CodePudding user response:

Models should be stored in a separate folder, not in the Home controller.

CodePudding user response:

It depends on your project. But most of the time is in separate folder or another layer.

You can create a folder in MVC project and move all view models to it or create another layer for view models.

Most of the time I use this layering :

  1. Core Helpers and Common method is in this layer
  2. Model Entities and EntityConfiguration is in this layer
  3. ViewModels ViewModels is in this layer
  4. Service Service and Contracts is in this layer
  5. WebFramework Extension method related to WebApplication is in this layer
  6. WebAppliaction Main project

Dependency:

WebAppliaction > WebFramework > Service > ViewModels > Model > Core

  • Related