【问题标题】:Proper usage of controller and model mvc正确使用控制器和模型 mvc
【发布时间】:2014-09-23 20:52:51
【问题描述】:

我目前正在做一个基于 mvc 的项目。我看到人们以不同的方式使用模型 n 控制器,我想知道根据 mvc 原理哪一个是正确的方法

方法一:

控制器:

  public ActionResult index()
    {
  return View();
    }

public string save ()
  {
return null;
  }

public string Update()
 {
return null;
 }

型号:

 public string xx {get;set;}
   public string yy {get;set;}

方法二:

控制器:

public ActionResult index()
{
return View();
}

型号:

 public string xx {get;set;}
public string yy {get;set;}

 public string save ()
      {
    return null;
      }

    public string Update()
     {
    return null;
     }

【问题讨论】:

  • 方法 1. 您的保存/更新操作应该是控制器中的 ActionResults(或类似的),而不是您的模型。在保存/更新时,您将更新您的模型并将其传递回您的视图。
  • 模型应该只包含属性?..我应该把数据填充函数放在哪里?在控制器或模型中?
  • 您可以从控制器中的操作调用业务逻辑层。

标签: asp.net-mvc asp.net-mvc-4


【解决方案1】:

虽然方法2更接近它,​​但我会说两者都不正确。

您应该将您的逻辑放在由您的控制器使用的单独服务中。

例子:

public ActionResult DoStuff() {
    var model = Service.save();
    return View(model);
}

public class Model {
    public string xx { get; set; }
    public string yy { get; set; }
}

public class Service 
{
    public string save ()
    {
        return null;
    }

    public string Update()
    {
        return null;
    }
}

控制器或模型中都不应该有业务逻辑。 They should only have a single responsibility。模型存储控制器返回的数据。控制器只是将它从服务接收到的数据转换为模型。

【讨论】:

  • 同意以上观点。有点像我在你的问题中所说的。 @GrimurD 将类称为 Service,这就是我所说的业务逻辑。
【解决方案2】:

Method 1.因为保存/更新是Action Method,它应该在Controller而不是模型内。

【讨论】:

  • 填充下拉菜单的功能怎么样?我应该把它放在哪里?..控制器或模型?
  • 控制器是一些对象,用于检查用户输入与业务逻辑的对应关系。
猜你喜欢
  • 2015-05-20
  • 2011-11-06
  • 1970-01-01
  • 2017-06-29
  • 2020-04-13
  • 2011-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多