crystyxn
crystyxn

Reputation: 1601

Model list becomes null when passing the view model to another method

I am using ASP.NET MVC5

my ExternalLoginConfirmationViewModel contains these:

 public List<Education> edus { get; set; }
 public List<Experience> workplaces { get; set; }

in my AccountController I declare the lists like so:

public List<Education> edus;
public List<Experience> workplaces;

I then populate them in ExternalLoginCallBack with no problem (debugged and they are as intended)

At the bottom I am trying to create the model and pass it to the "ExternalLoginConfirmation" like so:

 return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel
                    {
                        Email = loginInfo.Email,
                        FirstName = ExternalLoginLinkedIn.FirstName,
                        LastName = ExternalLoginLinkedIn.LastName,
                        Country = ExternalLoginLinkedIn.Country,
                        Summary = ExternalLoginLinkedIn.Summary,
                        LinkedinPictureUrl = ExternalLoginLinkedIn.LinkedinPictureUrl,
                        Gender = ExternalLoginLinkedIn.Gender,
                        Birthday = ExternalLoginLinkedIn.Birthday,
                        edus = edus,
                        workplaces = workplaces

                    });

So far so good, putting a breakpoint here shows the model to be populated as intended, educations and workplaces have the correct lists.

Now when its time for the next method:

 public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)

the ExternalLoginConfirmationModel contains all the data, except for the two lists (edus and workplaces), which they are null then I get an error. What am I missing? Is it the garbage collector?

Upvotes: 0

Views: 645

Answers (1)

Ygalbel
Ygalbel

Reputation: 5519

Because you call ExternalLoginConfirmation from HTML page, your model will bind only fields that you have in form.

That the reason all other fields pass and the lists become null.

You have two ways to solve this problem:

  1. Save edus and workplace in a store in server side, and take them back in ExternalLoginConfirmation method.

  2. Use @HiddenFor in you view to insert the lists as part of your form, so you will get them in ExternalLoginConfirmation method.

    Edit

You have another way to keep and fetch data. Use session object.

Session["edus"] = edus

And you take it back in next controller with a cast.

var edus = (List<Education>)Session["edus"]

Upvotes: 1

Related Questions