BattlFrog
BattlFrog

Reputation: 3397

How to access parameter value in controller method from RedirectToAction

After saving some data to the db, I pull the newly created userId from the db and I need to send it to the next View. I am using ReditectToAction to direct it and send the value. I have verified the value is making it to the redirect but I can't figure out how to grab it, because the model that comes in to AccountSetup is null. Where am i goig wrong?

method sending the id:

            var id = user.UserId;

            var accountModel = new AccountViewModel
            {
                UserId = id
            };

            return RedirectToAction("AccountSetup", "Home", accountModel.UserId);
        }

I have verified in debug, that accountModel.userId ha a value.

Method supposed to receive the id:

    public ActionResult AccountSetup(AccountViewModel model)
    {
        int id = model.UserId;

model is null.

Upvotes: 1

Views: 224

Answers (2)

Jason Berkan
Jason Berkan

Reputation: 8884

You need to use TempData to store anything during the redirect.

TempData["MyModel"] = accountModel;
return RedirectToAction("AccountSetup", "Home");

And then in the other action:

var accountModel = (AccountViewModel)TempData["MyModel"];
int id = accountModel.UserId;

Upvotes: 0

Ufuk Hacıoğulları
Ufuk Hacıoğulları

Reputation: 38468

return RedirectToAction("AccountSetup", "Home", accountModel.UserId);

You are not returning the model the action expects but just an id value. Model binder can't bind this value to AccountViewModel.UserId, it probably binds it to the id parameter in the default route. You are actually expecting a model of type AccountViewModel so you should send a AccountViewModel instance.

return RedirectToAction("AccountSetup", "Home",
                        new AccountViewModel {UserId = accountModel.UserId});

Upvotes: 2

Related Questions