【发布时间】:2019-10-15 22:01:38
【问题描述】:
我有一个返回视图的方法,在该视图中我想显示一些东西的列表。为了做到这一点,我需要一个带有房屋列表的模型。
Microsoft 的文档 (https://docs.microsoft.com/en-us/aspnet/core/mvc/overview?view=aspnetcore-2.2) 指出,选择和使用模型是控制器的责任,而模型的责任是封装业务逻辑。话虽如此,我不确定最佳做法:
控制器中的逻辑:
型号:
public class DepartmentViewModel
{
public IEnumerable<DepartmentDto> lstDepartments { get; set; }
}
控制器:
public class DepartmentController : Controller
{
private readonly IUnitOfWork _work;
private readonly IMapper _mapper;
public DepartmentController(IUnitOfWork work, IMapper mapper)
{
_work = work;
_mapper = mapper;
}
public async Task<IActionResult> Index(DepartmentViewModel viewmodel)
{
var lstAllDepartments = _work.DepartmentRepository.GetAll(); // All departments from the database.
var lstDepartmentsForViewmodel = _mapper.Map<IEnumerable<Core.Entities.Department>, IEnumerable<DepartmentDto>>(lstAllDepartments); // Map to DTO.
viewmodel.lstDepartments = lstDepartmentsForViewmodel;
return View(viewmodel);
}
}
模型中的逻辑:
型号:
public class DepartmentViewModel
{
private readonly IUnitOfWork _work;
private readonly IMapper _mapper;
public DepartmentViewModel(IUnitOfWork work, IMapper mapper)
{
_work = work;
_mapper = mapper;
var lstAllDepartments = _work.DepartmentRepository.GetAll(); // All departments from the database.
var lstDepartmentsForViewmodel = _mapper.Map<IEnumerable<Core.Entities.Department>, IEnumerable<DepartmentDto>>(lstAllDepartments); // Map to DTO.
lstDepartments = lstDepartmentsForViewmodel;
}
public IEnumerable<DepartmentDto> lstDepartments { get; set; }
}
控制器:
public class DepartmentController : Controller
{
private readonly IUnitOfWork _work;
private readonly IMapper _mapper;
public DepartmentController(IUnitOfWork work, IMapper mapper)
{
_work = work;
_mapper = mapper;
}
public async Task<IActionResult> Index()
{
DepartmentViewModel viewmodel = new DepartmentViewModel(_work, _mapper);
return View(viewmodel);
}
}
任何形式的指导将不胜感激。
【问题讨论】:
标签: c# json asp.net-core .net-core asp.net-core-mvc