我对MVC有些新意,所以原谅我的无知。我正在使用IoC(StructureMap),我需要将我认为是一组控件的实例传递给每个视图,因此我创建了ViewModels以便适应这一点。视图模型将填充控件实例,然后呈现视图。当用户执行POST时,控件不会传递回Action。
从控制器剪断
Private _WebControls As Products.Services.IControlsRepository
Private _customerRepo As Profiles.Services.ICustomerRepository
Sub New()
Me.New(ObjectFactory.GetInstance(Of Products.Services.IControlsRepository),
ObjectFactory.GetInstance(Of Profiles.Services.ICustomerRepository))
End Sub
Sub New(ByVal webRepo As Products.Services.IControlsRepository,
ByVal custRepo As Profiles.Services.ICustomerRepository)
_WebControls = webRepo
_customerRepo = custRepo
End Sub
<HttpGet()>
Function SendPassword() As ActionResult
Dim vm As New SendPasswordViewModel
vm.Controls = _WebControls
Return View(vm)
End Function
<HttpPost()>
Function SendPassword(ByVal model As SendPasswordViewModel) As ActionResult
If ModelState.IsValid Then
If _customerRepo.SendPassword(model.EmailAddress, model.Controls.WebControls.MacsDivision) = True Then
model.SendPasswordResponseMessage = "Email successfully sent. Please check your email for your password."
Else
model.SendPasswordResponseMessage = "No account was found with the email that you provided."
End If
End If
Return View("SendPassword", model)
End Function
答案 0 :(得分:0)
据我了解,您的控制器使用构造函数注入,并依赖于IControlsRepository
和ICustomerRepository
。由于在每个请求上创建了一个新的控制器实例,这意味着您的控制器将始终可以访问存储这些存储库的私有字段(_WebControls
和_customerRepo
)。因此,您无需拥有Controls
SendPasswordViewModel
属性。在您的POST操作中,您可以直接使用它:
<HttpPost()>
Function SendPassword(ByVal model As SendPasswordViewModel) As ActionResult
' Directly use _WebControls here instead of relying on model.Controls
...
End Function
因此,删除Controls
类的SendPasswordViewModel
属性,因为视图不需要存储库。它是与存储库一起使用的控制器。