Craig
Craig

Reputation: 18684

Passing an object in RedirectToAction

I have a controller that has received a POST back, and has processed what the user has requested. I then build an object, and now, want to RedirectToAction..

return RedirectToAction() ("Index", "Location", r);

Where r is the well named object I am working with. But on the target action, r is null.

public ActionResult Index(LocationByAddressReply location)

Now, I read a few posts on here about this, but am battling to understand.

An option put forward wasL

TempData["myObject"] = myObject;

But that seems ... strange. Not type safe. Is this the most suitable way to pass objects?

Upvotes: 1

Views: 8929

Answers (3)

educampver
educampver

Reputation: 3005

I don't think using TempData is the right solution, refer to this answer. You could instead, pass an anonymous object made of your r object. For example, if you have this:

public class UserViewModel 
{
    public int Id { get; set; }
    public string ReturnUrl { get; set; }
}

public ActionResult Index(UserViewModel uvm) 
{ 
    ...
}

you could pass that UserViewModel like this:

public ActionResult YourOtherAction(...)
{
    ...
    return RedirectToAction("Index", "Location", new 
                                                 { 
                                                     id = /*first field*/,
                                                     returnUrl = /*second field*/ 
                                                 });
}

ASP.NET MVC parses this into the object you are expecting as an argument in Index action. Give it a try if you haven't already switched your code for using TempData.

Upvotes: 1

von v.
von v.

Reputation: 17108

You can do this in two ways:

First option, if you have a simple model

return RedirectToAction("Index", "Location", new { Id = 5, LocationName = "some place nice" }); 

That one needs maintenance, think about if you need to later on add properties to your model. So you can be fancy and do it like this:

Second option, UrlHelper is your friend

return Redirect(Url.Action("Index", "Location", model));

The second option really is the right way of doing it. model is the object that you built and want to pass to your LocationController.

Upvotes: 4

Ken Clark
Ken Clark

Reputation: 2530

Yes you can get values using TempData on redirect. Your method should looks like:

public ActionResult YourRedirectMethod()

{
   TempData["myObject"]=r;
   return RedirectToAction() ("Index", "Location");

}

and

public ActionResult Index()
{
   LocationByAddressReply location=null;
   if(TempData["myObject"]!=null)
    {
          location=(LocationByAddressReply)TempData["myObject"];
    }
}

In this way you get values of your model that was previousely set on redirect method.

Upvotes: 2

Related Questions