Passing Model as Parameter in RedirectToAction: ASP.NET MVC Solution

When working with ASP.NET MVC, there may be situations where you need to pass a model as a parameter to the RedirectToAction method. This can be a bit tricky, but there is a solution.

First, let's take a look at the signature of the RedirectToAction method:

public RedirectToRouteResult RedirectToAction(
    string actionName,
    string controllerName,
    object routeValues
)

The routeValues parameter is an object that contains the parameters that will be passed to the action method. In this case, we want to pass a model.

To do this, we can use the TempData object. TempData is a dictionary that can be used to store data between requests.

Here's an example:

public ActionResult Index()
{
    MyModel model = new MyModel();
    TempData["MyModel"] = model;
    return RedirectToAction("Details");
}

public ActionResult Details()
{
    MyModel model = (MyModel)TempData["MyModel"];
    return View(model);
}

In this example, we create a new instance of MyModel in the Index action and store it in TempData. We then redirect to the Details action.

In the Details action, we retrieve the model from TempData and pass it to the view.

Note that TempData is only available for one subsequent request. After that, it will be cleared.

In conclusion, passing a model as a parameter to RedirectToAction in ASP.NET MVC can be accomplished by storing the model in TempData and retrieving it in the redirected action.

Click to rate this post!
[Total: 0 Average: 0]

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information