Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using RedirectToAction, routeValue losing reference properties

Tags:

asp.net-mvc

So if i do this in the first controller:

  public class AController:Controller
    {
            public ActionResult ActionOne()
            {
                 MyObject myObj = new MyObject()
                 myObj.Name="Jeff Atwood";
                 myObj.Age =60;
                 myObj.Address = new Address(40,"Street");

                 return RedirectToAction("ActionTwo", "BController", myObj );

             }
    }

In the second controller, myObj will come out ok, but Address will be null.

public class BController:Controller
        {
                public ActionResult ActionOne(MyObject obj)
                {
                     //obj.Address is null?

                 }
        }

Is this as expected? any way around it?

like image 455
Dan Avatar asked Apr 05 '09 09:04

Dan


3 Answers

You could use the TempData to store objects that will be available between two requests. Internally the default implementation uses the Session.

public class AController:Controller
{
    public ActionResult ActionOne()
    {
        MyObject myObj = new MyObject()
        myObj.Name = "Jeff Atwood";
        myObj.Age = 60;
        myObj.Address = new Address(40, "Street");
        TempData["myObj"] = myObj;
        return RedirectToAction("ActionTwo", "BController");

    }
}

public class BController:Controller
{
    public ActionResult ActionTwo()
    {
        MyObject myObj = TempData["myObj"] as MyObject;
        // test if myObj is defined. If ActionTwo is invoked directly it could be null
    }
}
like image 93
Darin Dimitrov Avatar answered Oct 20 '22 13:10

Darin Dimitrov


I did some further search and found Jon Kruger's blog. http://jonkruger.com/blog/2009/04/06/aspnet-mvc-pass-parameters-when-redirecting-from-one-action-to-another/

.net MVC frame work doesn't support this feature, but people have added support to mvccontrib. Unfortunately, I somehow cannot access mvccontrib.org. Can you let me know if this issue is solved? Thanks.

like image 42
Wei Ma Avatar answered Oct 20 '22 12:10

Wei Ma


I came across this same problem, with no obvious solution. While TempData comes in handy a lot, its nice to not have to use it all over because its rather hackish.

the best solution I found was to pass a new RouteValueDictionary

  return RedirectToAction("ActionTwo", "BController", new { MyObject = myObj } );
like image 44
f0ster Avatar answered Oct 20 '22 13:10

f0ster