0
的方法回報我只是想知道,以驗證我的視圖模型的方式。又該服務層
,用戶可以根據自己的只有一支球隊,所以我必須以某種方式檢查,如果他還沒有得到一個。
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次,這似乎是無用的。
確定。謝謝你的回答,但這是一個好習慣嗎? – pred
是的,如果你的服務代碼從兩處或兩處以上(網絡+ API爲例)一起使用。我認爲它更優雅,然後拋出異常並在以後捕獲它們。 – Nigrimmist