gpt4 book ai didi

asp.net-mvc - 在 ASP.NET MVC 中将引用数据加载到 View 模型中的可靠方法

转载 作者:行者123 更新时间:2023-12-04 06:32:46 25 4
gpt4 key购买 nike

我想要一种方法将引用数据的加载与 Controller 分离到 View 模型中。目前我有一个 View 模型,其中包含所选值和引用数据的属性:

public IEnumerable<SelectListItem> DayTypes { get; set; }
public int DayTypeId { get; set; }

并且数据是从 Controller 操作中的相关存储库中填充的:
model.DayTypes = _dayTypeRepository.GetAll().ToSelectList(d => d.Description, d => d.Identifier.ToString());

我想改变这一点,因为它用大量的存储库和代码污染了 Controller ,这些不是它关注的核心。所有这些依赖关系都让单元测试 Controller 变得很痛苦。

解决此问题的一种可能方法是让 View 模型类进行加载,这需要自定义模型绑定(bind)器使用 IoC 容器实例化它们以提供存储库依赖项。这是一个不错的选择吗?

CodeCampServer 中暗示了另一种我认为不错的方法。但不完整并被注释掉,涉及 View 模型中字段的属性:
[SelectListProvided(typeof(AllDaysSelectListProvider))]
public IEnumerable<SelectListItem> DayTypes { get; set; }

但是,我正在努力弄清楚如何以一种不需要对 MVC 框架进行一些重大重新配置的方式来实现这一点。

你怎么解决这个问题?

编辑:我想保留强类型 View 并避免将数据填充到 View 数据中。

进一步编辑:我还想要一个理想情况下独立于模型的解决方案,我的意思是,如果多个 View 模型需要相同的引用数据,这可以通过一段代码来实现。 Matt 的方法很有趣,但与 View 模型紧密耦合。

最佳答案

我会使用一个服务层,它会返回一个 POCO 对象,我会映射到一个 View 模型。所以我的 Controller Action 看起来像这样:

public ActionResult Index(int id)
{
var model = _service.GetModel(id);
var viewModel = Mapper.Map<Model, ViewModel>(model);
return View();
}

我也喜欢使用 action filters to avoid the mapping code重新来过,所以:
[AutoMap(typeof(Model), typeof(ViewModel))]
public ActionResult Index(int id)
{
var model = _service.GetModel(id);
return View(model);
}

这样,只有服务与 CRUD 存储库对话,而 Controller 与服务和映射层对话。

关于asp.net-mvc - 在 ASP.NET MVC 中将引用数据加载到 View 模型中的可靠方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5192724/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com