【问题标题】:ASP.NET MVC need to DRY similar controller actionsASP.NET MVC 需要 DRY 类似的控制器动作
【发布时间】:2019-11-06 19:28:59
【问题描述】:

在 ASP.NET MVC 中,我有 2 个“登录”操作,它们执行几乎相同的操作,但它们使用不同的模型并返回不同的视图。如何确保这些操作遵循 DRY 规则?

我尝试制作一个单独的函数来接收我需要的参数,但由于模型不同,我无法做到这一点。

这是两个动作:

Public Function Login(model As AccountViewModels.InternalLoginViewModel, location As String) As ActionResult
  ...

  If ... Then
     ...
     Return View(model)
  End If

  If Not ModelState.IsValid Then
     Return View(model)
  End If
  ...
  If authenticationResult.Success Then
     ...
  ElseIf ... Then
     Dim appUser As ApplicationUser = authService.GetApplicationUser(model.EmailUsername)
    ...
  ElseIf .. Then
     Return RedirectToAction("OldAppnuserRegister", MVC_CONTROLLER_ACCOUNT, authenticationResult.OldUser.GetRouteValues(location))
  ElseIf ... Then
     Return RedirectToAction("Index", MVC_CONTROLLER_MANAGE, New With {.userKey = authService.GetApplicationUser(model.EmailUsername).Key.ToString})
  End If
  ...
  Return View(model)
End Function

---------------

Public Function RepLogin(model As RepSessionViewModels.InternalLoginViewModel, location As String) As ActionResult
  ...

  If ... Then
     ...
     Return View("~/Views/RepSession/SelectProvider.vbhtml", model)
  End If

  If Not ModelState.IsValid Then
     Return View("~/Views/RepSession/SelectProvider.vbhtml", model)
  End If
  ...
  If authenticationResult.Success Then
     ...
  ElseIf ... Then
     Dim appUser As ApplicationUser = authService.GetApplicationUser(model.Email)
    ...
  ElseIf ... Then
     Return RedirectToAction("OldRepRegister", MVC_CONTROLLER_ACCOUNT, authenticationResult.OldUser.GetRouteValues(location))
  ElseIf ... Then
     Return RedirectToAction("Index", MVC_CONTROLLER_MANAGE, New With {.userKey = authService.GetApplicationUser(model.Email).Key.ToString})
  End If
  ...
  Return View("~/Views/RepSession/SelectProvider.vbhtml", model)
End Function

我将重复的代码替换为“...”以使其更具可读性。感谢所有帮助。谢谢。

【问题讨论】:

标签: asp.net-mvc vb.net dry


【解决方案1】:

根据发布的代码不清楚您需要什么。

但假设你真的需要两个不同的模型,你有不同的方法来做,请参考这篇文章http://www.dotnet-stuff.com/tutorials/aspnet-mvc/way-to-use-multiple-models-in-a-view-in-asp-net-mvc。 如果您仍有疑问,请正确澄清您的视图/模型之间的差异/相似之处。

以我个人的经验,这个场景只是一个糟糕的设计,你总是可以有一个基础模型、基础视图和部分视图来正确地完成它以避免重复代码。

【讨论】:

  • 这可能是糟糕的设计,这就是我问这个问题的原因。我确实需要 2 个不同的模型和 2 个不同的视图。不幸的是,在我的场景中,我的 2 个模型在同一个视图中是行不通的。
  • @Edit 你能为你的模型创建一个共享相同属性的基类或接口吗?
  • @zgood 这些模型有 3 个属性。其中 2 个继承自基类,但 1(电子邮件或电子邮件用户名)不同。除非我遗漏了什么,否则这对我的问题没有帮助。
【解决方案2】:

我得到的答案指向一个设计问题,我会假设它是并且没有其他方法可以解决我的问题。

我最终做的是使模型/操作/视图相同并完全删除 RepLogin。将用户要求从仅接受 RepLogin 中的电子邮件更改为也接受用户名。魔术字符串取决于我们是在 RepLogin 还是普通 Login 中的布尔值。

不是完美的解决方案,因为我必须更改我原本不想更改的内容,但它确实有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-10
    • 1970-01-01
    • 2017-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多