Betty Lazzari
Betty Lazzari

Reputation: 99

MVC Redirect to a different view in another controller

After a user has completed a form in MVC and the post action is underway, I am trying to redirect them back to another view within another model.

Eg. This form is a sub form of a main form and once the user has complete this sub form I want them to go back to the main form.

I thought the following might have done it, but it doesn't recognize the model...

//send back to edit page of the referral
return RedirectToAction("Edit", clientViewRecord.client);

Any suggestions are more that welcome...

Upvotes: 0

Views: 2921

Answers (3)

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93434

You can't do it the way you are doing it. You are trying to pass a complex object in the url, and that just doesn't work. The best way to do this is using route values, but that requires you to build the route values specifically. Because of all this work, and the fact that the route values will be shown on the URL, you probably want this to be as simple a concise as possible. I suggest only passing the ID to the object, which you would then use to look up the object in the target action method.

For instance:

return RedirectToAction("Edit", new {id = clientViewRecord.client.ClientId});

The above assumes you at using standard MVC routing that takes an id parameter. and that client is a complex object and not just the id, in which case you'd just use id = clientViewRecord.client

Upvotes: 1

karan ga
karan ga

Reputation: 11

If your intending to redirect to an action with the model. I could suggest using the tempdata to pass the model to the action method.

TempData["client"] = clientViewRecord.client;    
return RedirectToAction("Edit");


public ActionResult Edit ()
{
 if (TempData["client"] != null)
            {
               var client= TempData["client"] as Client ;
               //to do...
            }    
} 

Upvotes: 0

Chris Pratt
Chris Pratt

Reputation: 239290

A redirect is actually just a simple response. It has a status code (302 or 307 typically) and a Location response header that includes the URL you want to redirect to. Once the client receives this response, they will typically, then, request that URL via GET. Importantly, that's a brand new request, and the client will not include any data with it other than things that typically go along for the ride by default, like cookies.

Long and short, you cannot redirect with a "payload". That's just not how HTTP works. If you need the data after the redirect, you must persist it in some way, whether that be in a database or in the user's session.

Upvotes: 0

Related Questions