Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing a view model with RedirectToAction

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);
}
like image 354
jeremyo Avatar asked Sep 14 '25 02:09

jeremyo


1 Answers

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);

like image 172
Sam Axe Avatar answered Sep 15 '25 15:09

Sam Axe