[RESOLVED]Shifting from one view to another…

Given: Two strongly typed views for two action methods (Step1 and Step2).  Request comes in for Step 1 and is sent out no problem.  The post is processed using a property in the  first view model named SelectedPerson.  At this point I want, to send out the
strongly typed View for Step 2 using it’s viewmodel (VMStep2) created in the post back of step1.   This code doesn’t work…

    public ActionResult Step1()
    {
        var vm = new VMStep1();
        return View(vm);
    }
 
    [HttpPost]
    public ActionResult Step1(VMStep1 vm)
    {
        if (ModelState.IsValid)
        {
            var newVM = new VMStep2(vm.SelectedPerson);
            return RedirectToAction("Step2", newVM);
        }
        return View(vm);
    }
 
    public ActionResult Step2(VMStep2 vm)
    {
        return View(vm);
    }

When the post in Step1 calls the redirect, the content of the VM returned has lost all of its content, this is because MVC news up an instance based on the inbound request and NOT what I passed to it.

Please explain clearly, so that we can try to answer  

K, updated question. 

Hi,

Try this code:

    public ActionResult Step1()
    {
        var vm = new VMStep1();
        return View(vm);
    }
 
    [HttpPost]
    public ActionResult Step1(VMStep1 vm)
    {
        if (ModelState.IsValid)
        {
            return RedirectToAction("Step2", new {id = vm.SelectedPerson});
        }
        return View(vm);
    }
 
    public ActionResult Step2(int id)
    {
        // id is vm.SelectedPerson from Step1 view
        var newVM = new VMStep2(id);
        return View(vm);
    }

You can even redirect to other Controller, using: returnToAction(new { controller = "controllerName", action = "actionName", id = vm.SelectedPerson })

Have fun

I believe this is your problem:

v2kea60

var newVM = new VMStep2(vm.SelectedPerson);

You should map from VMStep1 to VMStep2 like this:

var newVM = new VMStep2 
                {
                   SelectedPerson = vm.SelectedPerson
                   //Other properties to map
                };

I assume your VMStep2 also has the SelectedPerson property.

 

Leave a Reply