Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 333
Craig Avatar asked Jan 01 '26 08:01

Craig


2 Answers

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.

like image 124
von v. Avatar answered Jan 03 '26 21:01

von v.


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.

like image 43
Ken Clark Avatar answered Jan 03 '26 23:01

Ken Clark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!