0

I'm calling another controller and action method here

    [HttpPost]
    public ActionResult Index(LoginModel loginModel)
    {
        if (ModelState.IsValid)
        { some lines of code . bla bla bla
          return RedirectToAction("indexaction","premiumcontroller");
        }
    }

Now, what happens is the indexaction of premiumcontroller is now executed.

How can i pass the values of loginmodel (or the loginmodel object) to the premiumcontroller? i cant figure it out. Thanks.

I'm using asp.net mvc 3.

tereško
  • 58,060
  • 25
  • 98
  • 150
vvavepacket
  • 1,882
  • 4
  • 25
  • 38

2 Answers2

1

You could pass them as query string parameters:

return RedirectToAction(
    "index",
    "premium", 
    new {
        id = loginModel.Id,
        username = loginModel.Username,
    }
);

and inside the index action of premium controller:

public ActionResult Index(LoginModel loginModel)
{
    ...
}

Another possibility is to use TempData:

[HttpPost]
public ActionResult Index(LoginModel loginModel)
{
    if (ModelState.IsValid)
    { 
        // some lines of code . bla bla bla
        TempData["loginModel"] = loginModel;
        return RedirectToAction("index", "premium");
    }
    ...
}

and inside the index action of premium controller:

public ActionResult Index()
{
    var loginModel = TempData["loginModel"] as LoginModel;
    ...
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • @patel.milanb, no we cannot use ViewData here. There is a redirect. In addition to this I would recommend against any usage of ViewData. – Darin Dimitrov Sep 25 '11 at 10:25
  • it works, but the url looks like this http://localhost:61852/premium?UserName=ronald&Password=123456 how can i remove that? – vvavepacket Sep 25 '11 at 11:33
  • @user963499, you can't remove that. If you remove it youwill no longer be able to fetch any data in the index action. As an alternative you could store your LoginModel into the database and then send only the id in the query string when redirecting: return `RedirectToAction("index", "premium", new { id = someId });`. Now the url will look like this: `localhost:61852/premium?id=1234` and inside the index action you will use this id to fetch back the model from the database. Or use `TempData` as shown in my second example. – Darin Dimitrov Sep 25 '11 at 11:35
1

you can use new keyword to pass the values in the controller action...

return RedirectToAction(
    "indexaction",
    "premium", 
    new {
        Id = loginModel.Id,
        UserName = loginModel.UserName,
        Password = loginModel.Password   
    }
);

in your other controller

public ActionResult indexaction(int id, string uName, string paswrd)
{
    // do some logic...
}
patel.milanb
  • 5,822
  • 15
  • 56
  • 92