Solved

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

Posted on 2013-06-29
4
561 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
In this video I am going to show you how to back up and restore Office 365 mailboxes using CodeTwo Backup for Office 365. Learn more about the tool used in this video here: http://www.codetwo.com/backup-for-office-365/ (http://www.codetwo.com/ba…

910 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

25 Experts available now in Live!

Get 1:1 Help Now