ASP.NET MVC需要DRY类似的控制器操作

在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",New With {.userKey = authService.GetapplicationUser(model.Email).Key.ToString})
  End If
  ...
  Return View("~/Views/RepSession/SelectProvider.vbhtml",model)
End Function

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

chengnuo2020 回答:ASP.NET MVC需要DRY类似的控制器操作

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

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

以我个人的经验,这种情况只是一个糟糕的设计,您始终可以使用基本模型,基本视图和局部视图来正确执行此操作,以避免重复代码。

,

我的答案是针对设计问题的,我将假设是的,没有其他方法可以解决我的问题。

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

不是完美的解决方案,因为我不得不更改本来不想更改的东西,但是它可以工作。

本文链接:https://www.f2er.com/3149433.html

大家都在问