tags:

views:

667

answers:

5

So if i do this in the first controller:

  public class AController:Controller
    {
            public ActionResult ActionOne()
            {
                 MyObject myObj = new MyObject()
                 myObj.Name="Jeff Attwood";
                 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?

A: 

Address is reference type, I think only "String" and value types like int, float etc can pass, because remember they are passing strings internally from on controller to another.

May be you may need to implement some serialization interface in order to do this (this is dependent upon the mode of transfer, xml, html or what form of transfer is used internally).

Akash Kava
+4  A: 

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 Attwood";
        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
    }
}
Darin Dimitrov
A: 

I have met the same problem. The TempData solution doesn't look too good because it makes unit testing hard. Is this a serialization problem as Akash pointed out?

Wei Ma
+2  A: 

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.

Wei Ma
A: 

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   );
f0ster