ASP.net MVC - 按次或每个动作一视图模型? [英] ASP.net MVC - One ViewModel per View or per Action?

查看:133
本文介绍了ASP.net MVC - 按次或每个动作一视图模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是个好主意,有按次单一视图模型和每个控制器的动作呢?

例如:

 公共ProjectController:控制器
{
    公众的ActionResult编辑(INT ID)
    {
        VAR项目= ...;

        返回查看(新ProjectEditViewModel(项目));
    }

    [HttpPost]
    公众的ActionResult编辑(ProjectEditViewModel模型)
    {
    }

    **要么**

    [HttpPost]
    公众的ActionResult编辑(项目型)
    {
    }

    [HttpPost]
    公众的ActionResult编辑(ProjectEditPostViewModel模型)
    {
    }
}
 

下面有三个选项,这是最好的?

  1. 使用相同的视图模型为我的POST / GET操作。
  2. 使用一个视图模型为我GET行动,我为我的POST操作的领域模型。
  3. 使用不同的视图模型为GET和不同的视图模型进行自检。
解决方案

使用不同的视图模式,为GET和POST操作是最好的和最灵活的设计。但使用了同样的看法型号为GET和POST操作也可以在90%的情况下,这是好的一个好的设计。因此,如果在方案中使用了同样的观点样板工程不要犹豫,再用它是这样的。

在其中不同视图模型用于GET和POST动作的情况下仍有这些类之间的一些关系:继承或组合物

Is it a better idea to have a single ViewModel per view or one per controller action?

Example:

public ProjectController : Controller
{
    public ActionResult Edit(int id)
    {
        var project = ...;

        return View(new ProjectEditViewModel(project));
    }

    [HttpPost]
    public ActionResult Edit(ProjectEditViewModel model)
    {
    }

    **OR**

    [HttpPost]
    public ActionResult Edit(Project model)
    {
    }

    [HttpPost]
    public ActionResult Edit(ProjectEditPostViewModel model)
    {
    }
}

Here are the three options, which is best?

  1. Use the same ViewModel for my POST/GET actions.
  2. Use a ViewModel for my GET action and my domain model for my POST action.
  3. Use a different ViewModel for GET and a different ViewModel for POST.

解决方案

Using a different view model for the GET and POST actions is the best and most flexible design. But using the same view model for the GET and POST actions also works in 90% of the cases and it is fine a good design. So if using the same view model works in your scenario don't hesitate to reuse it like this.

In the case where different view models are used for the GET and POST actions there is still some relation between those classes: inheritance or composition.

这篇关于ASP.net MVC - 按次或每个动作一视图模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆