Solved

MVC - Best way to pass viewModel data from one controller (form) to another

Posted on 2013-06-29
4
573 Views
Last Modified: 2013-07-02
I have two forms, PreRegister.html and Register.cshtml.  

PreRegister has a RadioButton group and I am trying to pass the user's selection - along with the CourseId that they had chosen to the Register controller/Form.

PreRegister.cshtml contains the following code:

 <div class="controls">
                    <label class="radio">
                        <input checked="checked" id="rbGrp" name="rbGrp" type="radio" value="1" /><label><b>Yes</b></label>
                       
                        <hr/>
                    </label>
                    <label class="radio">
                        <input id="rbGrp" name="rbGrp" type="radio" value="2" /><label><b>No</b></label>
                        
                    </label>
                </div>

Open in new window


In my controller, I want to capture the user's selection plus the CourseId that had been passed into the PreRegister controller and then pass these values in an object to the full Register controller/form

This is what I have so far:

public ActionResult PreRegister(int id)
        {
            var viewModel = new RegistrationViewModel();
            {
                viewModel.Enrollment.CourseId = id;
            }
            return View(viewModel);
        }

        [HttpPost]
        public ActionResult PreRegister(RegistrationViewModel viewModel)
        {
            var enrollment = new Enrollment();
            enrollment.CourseId = viewModel.Enrollment.CourseId;
            enrollment.IsHdco = viewModel.Enrollment.IsHdco 
            //how to get IsHdco value from user selection of rbGrp?


            return RedirectToAction("Register", viewModel?? enrollment??);
            //how to pass the enrollment object over to Register?
        }

        public ActionResult Register(int id)
        {
            CodeCamper.Model.Course course = _coursesRepository.GetById(id);

            var viewModel = new PageContentViewModel();
            {
                viewModel.PageContent = course.Description;
                viewModel.Course = course;
            }

            return View(viewModel);
        }

Open in new window


So I have 2 questions:
How do I get the value of the user selection from the radiobox group and translate it into a true/false?
How to I put this value plus CourseId into an object - either viewModel or Enrollment or something else and then transfer that as a parameter to the Register Controller that I want to geo to next?

Any help in figuring this out greatly appreciated.

RBS
0
Comment
Question by:RBS
  • 2
  • 2
4 Comments
 
LVL 21

Accepted Solution

by:
Craig Wagner earned 500 total points
ID: 39288114
Because the radiobutton isn't part of your viewmodel you're going to have to use the FormCollection on your post method.

[HttpPost]
public ActionResult PreRegister(RegistrationViewModel viewModel, FormCollection formCollection)
{
    // formCollection["rbGrp"] will return "1" or "2" depending which radiobutton was selected
}

Open in new window


As far as passing the information to another form action, you need to understand that what "RedirectToAction" is doing. Even though calling RedirectToAction looks like you're calling the new action directly, you aren't. Instead it is sending a 302 to the browser. The browser then requests the new URL. Given that understanding it becomes pretty clear there is really no way to directly pass the viewModel.

However, what MVC has given you is TempData. This uses the session state engine to preserve data across action redirects. So you would stuff whatever data you wanted to preserve into TempData and then pull it out in the new method.

[HttpPost]
public ActionResult PreRegister(RegistrationViewModel viewModel, FormCollection formCollection)
{
    TempData["SelectedRadioButton"] = formCollection["rbGrp"];
    TempData["SomeOtherValue"] = viewModel.SomeId;
    return RedirectToAction("Foo");
}

public ActionResult Foo()
{
    var selectedRadioButton =TempData["SelectedRadioButton"].ToString();
    var theId = (int)TempData["SomeOtherValue"]
}

Open in new window

0
 

Author Closing Comment

by:RBS
ID: 39288841
Thanks for this very clear explanation Craig with sample code.  One question arises - you said that "because the radiobutton isn't part of your model..."  

Is there an advantage of making a radiobutton part of my model?  Can you point to any resources that would explain how to do it or perhaps a sample line of code?  

Thanks again for your explanation!

RBS
0
 
LVL 21

Expert Comment

by:Craig Wagner
ID: 39288873
The advantage is that you get strong-typing in your model and you don't have to futz around with the FormCollection.

In the Model:

public class MyModel
{
    public string Choice { get; set; }
}

In the View:

@Html.RadioButtonFor( model => model.Choice, "1" )
@Html.RadioButtonFor( model => model.Choice, "2" )

In the Controller:

[HttpPost]
public ActionResult Foo( MyModel viewModel )
{
    if( viewModel.Choice == "2" )
    {
    }
    else if( viewModel.Choice == "1" )
    {
    }
}
0
 

Author Comment

by:RBS
ID: 39295363
Hi Craig:

A belated note to thank you for your additional explanation & code.  Clear and just what I needed.    Thanks,

RBS
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Javascript to set controls visibility 5 38
Reading the Web.Config using IIS 7.5? 4 36
Help with error when uploading excel file 3 29
Regular expression help 2 25
Summary Displaying images in RichTextBox is a common requirement with limited solutions available. Pasting through clipboard or embedding into RTF content only support static images.  This article describes how to insert Windows control objects int…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

803 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question