【发布时间】:2013-06-17 08:25:37
【问题描述】:
ASP.NET MVC4 - 基本上我曾经在我的控制器中拥有我的所有业务逻辑(我试图将其放入域模型中)。 但是我不太清楚我的所有业务逻辑是否应该放入域模型中,或者是否应该保留一些在控制器中?
例如,我得到了如下所示的控制器操作:
[HttpPost]
public ActionResult Payout(PayoutViewModel model)
{
if (ModelState.IsValid)
{
UserProfile user = PublicUtility.GetAccount(User.Identity.Name);
if (model.WithdrawAmount <= user.Balance)
{
user.Balance -= model.WithdrawAmount;
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
ViewBag.Message = "Successfully withdrew " + model.WithdrawAmount;
model.Balance = user.Balance;
model.WithdrawAmount = 0;
return View(model);
}
else
{
ViewBag.Message = "Not enough funds on your account";
return View(model);
}
}
else
{
return View(model);
}
}
现在是否应该将所有逻辑放入域模型中的方法中,使操作方法看起来像这样?
[HttpPost]
public ActionResult Payout(PayoutViewModel model)
{
var model = GetModel(model);
return View(model);
}
或者你会怎么做?
【问题讨论】:
-
我建议将所有代码放入域模型中。它使控制器更清洁。
-
@DarrenDavies 所以即使 ModelState.IsValid 也应该放入域模型中?
-
不,
ModelState.IsValid是 MVC 的东西,我会将if条件部分放入域中返回模型或抛出异常。 -
这是关于 FatControllers 的重要读物codebetter.com/iancooper/2008/12/03/the-fat-controller
标签: c# .net asp.net-mvc asp.net-mvc-4