When using RedirectToAction, routeValue lose reference properties

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 exit normally, but the address will be empty.

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

                 }
        }

Is this as expected? in any way around him?

+5
source share
5 answers

You can use TempData to store objects that will be available between two queries. Internally, the default implementation uses a 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
    }
}
+8
source

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

.net MVC , mvccontrib. , - mvccontrib.org. , ? .

+2

, . TempData , , .

, , RouteValueDictionary

  return RedirectToAction("ActionTwo", "BController", new { MyObject = myObj } );
+2

, , "String" , int, float .., , .

, ( , xml, html ).

+1
source

I ran into the same problem. TempData's solution does not look too good, because it requires rigorous module testing. Is this a serialization issue, as Akash noted?

0
source

All Articles