Search code examples
asp.net-mvcmodel-view-controllerarearedirecttoaction

Redirect to Action in another area that accepts a model


There are a few questions on SO about redirecting to an action in another area but none answers a more specific question that I have.

Let's say I have an Action like this:

 public virtual ActionResult ActioName(ViewModel model)
 {
    return View(model);
 }

If there wouldn't be a model parameter, you would do the following to redirect to this action from another area:

return RedirectToAction("ActioName", "ControllerName", new { Area = "" });

I tried including a model as well as the area in multiple ways but didn't work. I need a way to include both the area name and model. Thank you.

EDIT: TempData is not an answer, I do not want to modify the target controller.


Solution

  • Use RedirectToRoute instead, where namedRoute provides the controller name and action instead of retrieving from the url, like the default route does.

    return RedirectToRoute("namedRoute",model);
    

    Or possibly:

    return RedirectToRoute("namedRoute",new { model: model });
    

    Or to redirect into an area

    return RedirectToRoute("Area_namedRoute",model);
    

    Just be aware that this will trigger a get request instead of a post. That has a few limitations to be aware of:

    1. Browsers have limitations on the length of a url, IE being more troublesome here
    2. Actions methods with [HttpPost] attributes can't be triggered this way
    3. Embedding large amounts of data in a url is a security risk. What happens if a user shares their web page with a friend.
    4. Get requests are considered by search engines to be free from side-effects, they are considered read-only.

    That being said, see ASP.NET MVC: RedirectToAction with parameters to POST Action if you need to post instead of get.