开发者

ASP .NET MVC ViewModel object is not preserved

I am sort of new to MVC so pardon my ignorance. I am using IoC ( StructureMap ) and I have a need to pass in an instance of what I consider to be a s开发者_开发知识库et of Controls to each view, so I have created ViewModels in order to accomodate this. The view model is populated with an instance of the Controls and the View is then rendered. When a user performs a POST, the Controls are not being passed back to the Action.

Snip from the Controller

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


As I understand it your controller uses constructor injection and depends on IControlsRepository and ICustomerRepository. As a new controller instance is created on each request this means that your controller will always have access to the private fields where you stored those repositories (_WebControls and _customerRepo). As a consequence to this you don't need to have the Controls property of SendPasswordViewModel. In your POST action you could directly use it:

<HttpPost()>
Function SendPassword(ByVal model As SendPasswordViewModel) As ActionResult
    ' Directly use _WebControls here instead of relying on model.Controls
    ...
End Function

So remove the Controls property of the SendPasswordViewModel class as the view doesn't need a repository. It's the controller that works with the repository.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜