应该从服务层返回什么方法

时间:2016-12-04 22:35:11

标签: asp.net-mvc service

我只是想知道验证我的viewmodel的方法。

用户只能拥有一个团队,所以如果他没有,我必须以某种方式检查。

    public ActionResult AddTeam(TeamCreatingViewModel teamToAdd)
    {
        if (ModelState.IsValid)
        {
            //check if the user has got a team
            if (!TeamService.checkIfUserHasCreatedTeam(User.Identity.GetUserId()))
            {
                //if not then allow him to create one
                if (!TeamService.addTeam(teamToAdd, User.Identity.GetUserId()))
                {
                    ViewBag.Info = "Success";
                    return View("Info");
                }
                else
                {
                    ViewBag.Info = "It was impossible to create a new team";
                    return View("Error");
                }
            }
            else
            {
                ViewBag.info = "You have a team!";
                return View("Error");
            }
        }
        else
        {
            return View("TeamCreatingForm", teamToAdd);
        }
    }

或者下面的解决方案会更好吗?

    public ActionResult AddTeam(TeamCreatingViewModel teamToAdd)
    {
        if (ModelState.IsValid)
        {
            if (!TeamService.addTeam(teamToAdd, User.Identity.GetUserId())) //<--- now it is checking and adding (if allowed)
            {
                ViewBag.Info = "Success";
                return View("Info");
            }
            else
            {
                ViewBag.Info = "It was impossible to create a new team";
                return View("Error");
            }
        }
        else
        {
            return View("TeamCreatingForm", teamToAdd);
        }
    }

如果发生错误(以及哪种类型),我如何报告(来自服务层)?在第二种情况下,用户不会知道做错了什么。 在第一种情况下,我必须得到一个实体对象2次,似乎没用。

1 个答案:

答案 0 :(得分:0)

您可以通过抛出参数来报告业务层中的错误,例如

public bool AddItem(string name, out List<string> errors){...}// or just string with error