I have an MVC application where I want to display a drop-down list with information from a database.
The drop-down list will display information from the Cars database using the Make table, which is the brand of the car.
So, in my opinion, I will have something like:
@model VectorCheck.ViewModels.CarsViewModel ... @Html.DropDownListFor(modelItem => Model.MakeId, Model.Makes) ...
So somehow I need to get the view model in the make list.
So, I can have some logic to go with this, say only cars that are painted red.
var redCars = _unitOfWork.Cars(x => x.Colour == "Red");
So my question is where is the best place to put the logic for this request. Whether it should be in the Model view or controller.
As I can see, I have two options.
Option 1: controller.
public ActionResult Edit(int id) { var car = _unitOfWork.CarRepository.Get(id); var carMakes = _unitOfWork.CarMakeRepository.Where(x => x.Colour == "Red").Select(u => new SelectListItem { Value = u.CarMakeId.ToString(), Text = u.Name }); return View("Edit", new InsertUpdateCarViewModel(car, carMakes)); }
ViewModel
public Car Car { get; set; } public IEnumerable<SelectListItem> CarMakes { get; set; } InsertUpdateCarViewModel(Car car, IEnumerable<SelectListItem> carMakes) { Car= car; CarMakes = carMakes; }
So, in this example, I get carMakes in the controller and pass them to viewModel, which is just a container.
Opon 2: ViewModel
public ActionResult Edit(int id) { var car = _unitOfWork.CarRepository.Get(id); return View("Edit", new InsertUpdateCarViewModel(car)); }
ViewModel
public Car Car { get; set; } public IEnumerable<SelectListItem> CarMakes { get; set; } InsertUpdateCarViewModel(Car car) { Car= car; CarMakes = _unitOfWork.CarMakeRepository.Where(x => x.Colour == "Red").Select(u => new SelectListItem { Value = u.CarMakeId.ToString(), Text = u.Name }); }
So, in this option, I put the logic to get the correct models in the view model. It is more than a container.
So I want to know which of these methods is the right way to do this?