Solved

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

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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
VB.Net Tranfer data between to VB.Net apps 8 40
how to just get time from a date 6 34
MYSQL responding very slow 3 27
Code enhancement 4 22
Welcome my friends to the second instalment and follow-up to our Minify and Concatenate Your Scripts and Stylesheets (http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/A_4334-Minify-and-Concatenate-Your-Scripts-and-Stylesheets.html)…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

821 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