call controller and action method and pass model v

2019-09-02 13:20发布

问题:

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.

回答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...
}


回答2:

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;
    ...
}