【发布时间】:2012-01-24 21:55:24
【问题描述】:
我对 ASP.NET MVC 3 还是相当陌生。我遇到过视图模型及其用于将数据从控制器传递到视图的用途。在我最近的question on model binding 中,两位专家建议我也应该使用视图模型进行模型绑定。
这是我以前没有遇到过的。但是两个人都向我保证,这是最好的做法。有人能解释一下为什么视图模型更适合模型绑定吗?
这是一个示例情况:我的域模型中有一个简单的类。
public class TestParent
{
public int TestParentID { get; set; }
public string Name { get; set; }
public string Comment { get; set; }
}
这是我的控制器:
public class TestController : Controller
{
private EFDbTestParentRepository testParentRepository = new EFDbTestParentRepository();
private EFDbTestChildRepository testChildRepository = new EFDbTestChildRepository();
public ActionResult ListParents()
{
return View(testParentRepository.TestParents);
}
public ViewResult EditParent(int testParentID)
{
return View(testParentRepository.TestParents.First(tp => tp.TestParentID == testParentID));
}
[HttpPost]
public ActionResult EditParent(TestParent testParent)
{
if (ModelState.IsValid)
{
testParentRepository.SaveTestParent(testParent);
TempData["message"] = string.Format("Changes to test parents have been saved: {0} (ID = {1})",
testParent.Name,
testParent.TestParentID);
return RedirectToAction("ListParents");
}
// something wrong with the data values
return View(testParent);
}
}
因此,在 HTTP POST 到达时调用的第三个操作方法中,我使用 TestParent 进行模型绑定。这感觉很方便,因为生成 HTTP POST 请求的浏览器页面包含 TestParent 的所有属性的输入字段。我实际上认为这也是 Visual Studio 为 CRUD 操作提供的模板的工作方式。
但是我得到的建议是第三个操作方法的签名应该是public ActionResult EditParent(TestParentViewModel viewModel)。
【问题讨论】:
-
IMO,使用视图模型或模型取决于具体情况。如果页面仅使用特定模型的属性,那么我认为可以将视图强输入到该模型并继续。但是,如果有一些元素本身不是模型的一部分,那么这就是视图模型发挥作用的地方。创建视图模型只是为了将模型表示为视图类型,这违背了 DRY 代码的概念。这是其中一个概念,如果您询问 10 位开发人员,您将得到 12 个答案。底线是使用模型不会(据我所知)违反 MVC 的概念。
标签: asp.net-mvc-3 viewmodel model-binding