如何避免将域逻辑控制器? [英] How to avoid placing domain logic in controller?

查看:101
本文介绍了如何避免将域逻辑控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PRO ASP.NET MVC的书:

On PRO ASP.NET MVC book:

这当然是可能把域名
  逻辑到控制器,即使
  你不应该,只是因为它似乎
  权宜之计一些pressured时刻。

It is certainly possible to put domain logic into a controller, even though you shouldn’t, just because it seems expedient at some pressured moment.

只是一个人为的例子,如果应用程序不允许负级,在那里把量的变化到1?如果我们按照该域的逻辑不应该放置在控制器的原则,这肯定是不建议使用:

Just a contrived example, if the application doesn't allow negative order, where to put the changing of quantity to 1? If we follow the principle that domain logic shouldn't be placed in controller, this is certainly not advisable to use:

[AcceptVerbs(HttpVerbs.Post)]        
public ActionResult PlaceOrder(Order order)
{
 if (ModelState.IsValid)
 {
  order.Submit();
  return View("Thanks", order);
 }
 else
 {
    if (order.Quantity <= 0)
    {
        ModelState.Remove("Quantity");
        order.Quantity = 1;  
    }
    return View(order);
 }
}

所以下面code是正确的code,它坚持MVC的原则,即它遵循的关注点分离,如果是域逻辑你不应该看到它的控制器code。所以,这就是我试图把域逻辑型号:

So the following code is the right code that adheres to MVC principle, i.e. it follows separation of concerns, if it's domain logic you should not see its code in controllers. So this is how I tried placing the domain logic in Model:

public class Order : IDataErrorInfo
{
 public int OrderId { set; get; }
 public int ProductId { set; get; }
 public int Quantity { set; get; }

 public string Error { get { return null; } }

 public string this[string propName]
 {
  get
  {
   if (propName == "Quantity" && Quantity <= 0)
   {
    Quantity = 1;
    return "0 or negative quantity not allowed, changed it to 1";
   }
   else
    return null;

  }
 }
}

控制器(SAN的域逻辑):

Controller (sans the domain logic):

[AcceptVerbs(HttpVerbs.Post)]        
public ActionResult PlaceOrder(Order order)
{
 if (ModelState.IsValid)
 {
  order.Submit();
  return View("Thanks", order);
 }
 else
 {
  // Response.Write(order.Quantity.ToString()); // this was changed in Model
  return View(order); // but the View didn't reflect that fact
 }
}

这种做法的唯一问题,该模型(订单)不能影响的ModelState,而这样的程序总是显示无论是由用户上次输入。

The only problem with that approach, the Model(Order) can't influence the ModelState, and such, the program always display whatever is last entered by the user.

什么是最好的办法,所以我仍然能避免放置域逻辑控制器和视图仍然能够反映出模型的属性值?

What's the best approach so I can still avoid placing domain logic in controller and the View is still able to reflect the values of Model's properties?

推荐答案

确认不是控制器的任务。你可以把所有需要的逻辑不同的模块中,有刚刚传播完成的请求。

Validation is not controllers task. You can Put all required logic in different module, and just propogate requests there.

这篇关于如何避免将域逻辑控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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