Solved

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

Posted on 2013-06-29
4
551 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Hi Craig:

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

RBS
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Suggested Solutions

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

763 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now