Solved

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

Posted on 2013-06-29
4
597 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

MIM Survival Guide for Service Desk Managers

Major incidents can send mastered service desk processes into disorder. Systems and tools produce the data needed to resolve these incidents, but your challenge is getting that information to the right people fast. Check out the Survival Guide and begin bringing order to chaos.

Question has a verified solution.

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

It seems a simple enough task, yet I see repeated questions asking how to do it: how to pass data between two forms. In this article, I will show you the different mechanisms available for you to do just that. This article is directed towards the .N…
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…
Are you ready to implement Active Directory best practices without reading 300+ pages? You're in luck. In this webinar hosted by Skyport Systems, you gain insight into Microsoft's latest comprehensive guide, with tips on the best and easiest way…
This video shows how to use Hyena, from SystemTools Software, to update 100 user accounts from an external text file. View in 1080p for best video quality.

738 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