3

I want to pass a view model from one action to another action with the RedirectToAction, however when doing this, I get an error stating that "Object reference not set to an instance of an object", when i have already populated the model with data from the controller, but it is null in the view. I want to pass the data from Login to LoggedIn. I dont want to use query string as this can be easily manipulated by a hacker

[HttpPost]
public ActionResult Login(User account)
{
    using (TestDBEntities db = new TestDBEntities())
    {
        var user = db.Users.SingleOrDefault(u => u.Email == account.Email && u.Password == account.Password);
        if (user != null)
        {
            Session["USER"] = user.UserID;
            var model = new UserAccountViewModel{UserAccount = user};
            return RedirectToAction("LoggedIn", model);
        }

        ModelState.AddModelError("", "User credentials are invalid");
    }

    return View("Login");
}

public ActionResult LoggedIn(UserAccountViewModel model)
{
    return View(model);
}
Ziv Weissman
  • 4,400
  • 3
  • 28
  • 61
jeremyo
  • 71
  • 10

1 Answers1

2

RedirectToAction kicks a 30x back to the browser. Your view model won't survive that kind of trip.

You could either store your view model in the TempData collection, Or just call the function you want: return mySuperCoolControllerInstance.ActionsAreJustMethods(viewModel)

in your case it would be: return this.LoggedIn(model);

Sam Axe
  • 33,313
  • 9
  • 55
  • 89