CRUD 编辑视图的输入模型与视图模型
对于我的存储库中的每个实体,我都有一个视图模型和一个输入模型。我发现使用输入模型来存储关系 ID(而不是外部实体)可以使渲染选择列表变得更容易,但是您将哪个模型传递到编辑视图进行渲染,视图模型或输入型号?
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);
}
从长远来看,哪个更容易维护?
For each entity in my repository, I have a view model and an input model. I find having an input model to store relational IDs (as opposed to foreign entities) makes rendering select lists easier, but which model do you pass to your Edit view for rendering, View Model or Input Model?
Sample POST action for Category
entity:
[HttpPost]
public ActionResult Edit(CategoryInputModel inputModel)
{
// map inputModel to entity and persist
// ...
}
View Model:
[HttpGet]
public ActionResult Edit(int id)
{
var category = _unitOfWork.CurrentSession.Get<Category>(id);
var viewModel = Mapper.Map<Category, CategoryViewModel>(category);
return View(viewModel);
}
In this case the edit view form would take care of providing the correct input model fields for the POST action.
Input Model:
[HttpGet]
public ActionResult Edit(int id)
{
var category = _unitOfWork.CurrentSession.Get<Category>(id);
var inputModel = Mapper.Map<Category, CategoryInputModel>(category);
return View(inputModel);
}
Which is easier to maintain in the long run?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我现在使用的输入模型不包含 ID。我将实体 ID 保留为操作参数,如下所示:
I'm now using an input model that does not contain an ID. I keep the entity ID as the action parameter, like so:
当详细信息/编辑屏幕完全相同时,我使用相同的 ViewModel。
但正如您所注意到的,当屏幕不同时,我确实使用 InputModel,我将它们称为 FormModel。
我认为使用 AutoMapper 维护 ViewModel 非常便宜。使用 .AssertConfigurationIsValid() (我忘记了确切的方法名称)可以立即告诉您域/业务对象和表单/视图模型之间的不同步情况。
I use the same ViewModel when the detail/edit screens are exactly the same.
But like you've noticed, when the screens are different I do use a InputModel, I call them FormModels.
I consider ViewModels really cheap to maintain with AutoMapper. Using .AssertConfigurationIsValid() ( I forget the exact method name ) tells you right away what went out of synch between domain/buisness objects and Form/View Models.