如何在MVC中建模发布的数据?

时间:2011-07-27 12:11:36

标签: asp.net-mvc model-view-controller design-patterns viewmodel

我想我在ViewModel中了解了MVC,但在进行更新和删除时,似乎应该有一个独特的模型发布到控制器。我注意到默认的剃刀控制器使用ViewBag来保存选择列表。

我想这会使ViewModel(域实体真的)在返回途中重复使用,因为它被剥夺了不必要的数据。但是在使用视图模型时似乎诉诸ViewBag似乎没有意义,因为视图模型可以包含Selectlist等等。

所以我的问题是什么样的模式可用于制作不同的“发布数据”模型? (从Esposito的MVC 2书中得到这个术语)如何将发布的数据模型与视图模型相关联?例如,我似乎会尝试将已发布的数据模型包含在视图模型中。我是MVC的新手,也不是来自web-forms背景。我真的想了解用于建模将被发送到控制器的数据的最佳模式。

1 个答案:

答案 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