【问题标题】:Input Model vs View Model for CRUD Edit ViewCRUD 编辑视图的输入模型与视图模型
【发布时间】:2011-04-21 14:46:16
【问题描述】:

对于存储库中的每个实体,我都有一个视图模型和一个输入模型。我发现有一个输入模型来存储关系 ID(而不是外部实体)使渲染选择列表更容易,但是您将哪个模型传递给您的编辑视图进行渲染,View ModelInput型号

Category 实体的示例 POST 操作:

[HttpPost]
public ActionResult Edit(CategoryInputModel inputModel)
{
    // map inputModel to entity and persist
    // ...
}

查看模型:

[HttpGet]
public ActionResult Edit(int id)
{
    var category = _unitOfWork.CurrentSession.Get<Category>(id);
    var viewModel = Mapper.Map<Category, CategoryViewModel>(category);
    return View(viewModel);
}

在这种情况下,编辑视图表单将负责为 POST 操作提供正确的输入模型字段。

输入模型:

[HttpGet]
public ActionResult Edit(int id)
{
    var category = _unitOfWork.CurrentSession.Get<Category>(id);
    var inputModel = Mapper.Map<Category, CategoryInputModel>(category);
    return View(inputModel);
}

从长远来看,哪个更容易维护?

【问题讨论】:

  • 您可以添加您的视图和输入模型代码吗?我不知道,但根据我的经验,我总是看到将同一个模型用于两种目的。

标签: asp.net-mvc forms viewmodel


【解决方案1】:

我现在使用的输入模型不包含 ID。我将实体 ID 保留为操作参数,如下所示:

[HttpPost]
public ActionResult Edit(Guid id, CategoryInputModel inputModel)
{
    var category = _categoryRepository.Get(id);
    // do mappings from inputModel to category and save
    // ...
}

【讨论】:

    【解决方案2】:

    当细节/编辑屏幕完全相同时,我使用相同的 ViewModel。

    但正如您所注意到的,当屏幕不同时,我确实使用 InputModel,我称它们为 FormModel。

    我认为使用 AutoMapper 维护 ViewModel 真的很便宜。使用 .AssertConfigurationIsValid()(我忘记了确切的方法名称)会立即告诉您域/业务对象和表单/视图模型之间的不同步。

    【讨论】:

      猜你喜欢
      • 2018-08-02
      • 2011-08-24
      • 1970-01-01
      • 2020-06-20
      • 2013-09-13
      • 1970-01-01
      • 2014-12-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多