c# - 如何在 ASP.NET MVC3 中填充 ViewModel

标签 c# asp.net-mvc-3 viewmodel fill

在我的 Controller 中,我有一个来 self 的域模型ProductInfo类,我需要它的一些信息来填充我的 View 模型 ProductStatsVM

如何填充 View 模型?我听说了三种可能的方式:

  1. 直接从 Controller 填充 View 模型(不好,我想让我的 Controller 保持 slim )
  2. 通过使用 View 模型构造函数并将域模型作为参数传递。 (我必须为我想使用的每个域模型类创建一个构造函数)
  3. 通过使用 Fill() 方法。 (我在网上看到它,不知道它是如何工作的,我猜这样 ViewModel 应该知道服务层并创建耦合)。

我知道有像 AutoMapper 这样的工具,我确实会使用它,但在我想了解如何在不使用任何其他工具的情况下从 Controller 填充 View 模型的逻辑之前。

最佳答案

这个想法是您的 Controller 操作查询某个存储库以获取域模型。然后它将这个域模型传递给负责将其转换为 View 模型的映射层,最后将 View 模型传递给 View :

public ActionResult Index(int id)
{
    ProductInfo product = repository.GetProductInfo(id);
    ProductViewModel viewModel = Mapper.Map<ProductInfo, ProductViewModel>(product);
    return View(viewModel);
}

你甚至可以通过引入一个自定义 Action 过滤器来让你的 Controller 更 slim ,它会自动拦截 OnActionExecuted 中的模型。事件并调用映射层以将其替换为相应的 View 模型,这样您的 Controller 操作现在变为:

[AutoMapTo(typeof(ProductViewModel))]
public ActionResult Index(int id)
{
    ProductInfo product = repository.GetProductInfo(id);
    return View(product);
}

当然,现在 View 被强类型化为 ProductViewModel:

@model ProductViewModel
...

由您来实现Mapper.Map<TSource, TDest>方法。如果你不想自己实现它,你可以下载 AutoMapper它已经为您提供了这种方法。

映射层是 MVC 应用程序的一部分。它必须知道来自服务层的域模型和 MVC 应用程序中定义的 View 模型,以便能够执行映射。

不要在 View 模型中使用构造函数(默认的无参数构造函数除外)。如果 View 模型在您的 POST 操作中没有无参数构造函数,则默认模型绑定(bind)器将阻塞,您将不得不实现自定义模型绑定(bind)器。

关于c# - 如何在 ASP.NET MVC3 中填充 ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9364563/

相关文章:

mono - MvvmCross 中单个 View 的两个 ViewModel

c# - viewModel之间使用MVVM方式的接口(interface)进行通信

c# - 在实现接口(interface)以满足 StyleCop 时如何自动化属性/方法 header

c# - 类库不识别 CommandManager 类

asp.net-mvc-3 - .NET MVC 3 以编程方式设置布局

asp.net-mvc - MVC 和 Razor 中 Html.TextboxFor 和 Html.EditorFor 的区别

c# - MVC4 C# 从数据库中填充 View 模型中的数据

c# - 最小公倍数

asp.net-mvc-3 - 禁用 ASP.NET-MVC3 中 unicode 字符的编码

firefox - 带有自动填充功能的 Knockoutjs 密码绑定(bind)在 Firefox 中不起作用