我想我在ViewModel
中了解了MVC
,但在进行更新和删除时,似乎应该有一个独特的模型发布到控制器。我注意到默认的剃刀控制器使用ViewBag
来保存选择列表。
我想这会使ViewModel
(域实体真的)在返回途中重复使用,因为它被剥夺了不必要的数据。但是在使用视图模型时似乎诉诸ViewBag
似乎没有意义,因为视图模型可以包含Selectlist
等等。
所以我的问题是什么样的模式可用于制作不同的“发布数据”模型? (从Esposito的MVC 2书中得到这个术语)如何将发布的数据模型与视图模型相关联?例如,我似乎会尝试将已发布的数据模型包含在视图模型中。我是MVC
的新手,也不是来自web-forms
背景。我真的想了解用于建模将被发送到控制器的数据的最佳模式。
答案 0 :(得分:2)
我经常使用相同的视图模型将其传递到编辑/更新视图并在POST操作中接收它。这是常用的模式:
public ActionResult Edit(int id)
{
DomainModel model = ... fetch the domain model given the id
ViewModel vm = ... map the domain model to a view model
return View(vm);
}
[HttpPost]
public ActionResult Edit(ViewModel vm)
{
if (!ModelState.IsValid)
{
// there were validation errors => redisplay the view
// if you are using dropdownlists because only the selected
// value is sent in the POST request you might need to
// repopulate the property of your view model which contains
// the select list items
return View(vm);
}
DomainModel model = ... map the view model back to a domain model
// TODO: process the domain model
return RedirectToAction("Success")
}
就域模型和视图模型之间的映射而言,我建议您AutoMapper。