RedirectToAction from different controller and with parameters/routevalues not working

memeonline picture memeonline · Aug 16, 2012 · Viewed 7.7k times · Source

I’m trying to call a action method from different controller but it´s not working. It simply skips the RedirectToAction

here's my code:

public ActionResult sendPolicy(TempPoliciesUpload TempPolicy)
        {
            return RedirectToAction("Insert", "Policies", new { tempPolicy = TempPolicy });
        }

Please help.

Answer

Darin Dimitrov picture Darin Dimitrov · Aug 16, 2012

You cannot send complex objects when redirecting. You will have to include each property as query string parameter. And this works only with simply scalar properties.

public ActionResult sendPolicy(TempPoliciesUpload TempPolicy)
{
    return RedirectToAction("Insert", "Policies", new 
    { 
        id = TempPolicy.Id,
        prop1 = TempPolicy.Prop1,
        prop2 = TempPolicy.Prop2,
        ...
    });
}

If you have complex properties you will have to include them as well so that the default model binder is able to bind the model in the target action from the query string parameters:

public ActionResult sendPolicy(TempPoliciesUpload TempPolicy)
{
    return RedirectToAction("Insert", "Policies", new RouteValueDictionary
    {
        { "id", TempPolicy.Id },
        { "prop1", TempPolicy.Prop1 },
        { "prop2", TempPolicy.Prop2 },
        { "prop3.subprop1", TempPolicy.Prop3.SubProp1 },
        { "prop3.subprop2", TempPolicy.Prop3.SubProp2 },
        ...
    });
}

and your target action:

public ActionResult Insert(TempPoliciesUpload TempPolicy)
{
    ...
}

Another possibility is to persist this object in your backend before redirecting and then pass only the id:

public ActionResult sendPolicy(TempPoliciesUpload TempPolicy)
{
    int id = Repository.Save(TempPolicy);
    return RedirectToAction("Insert", "Policies", new { id = id });
}

and in your target action:

public ActionResult Insert(int id)
{
    TempPoliciesUpload TempPolicy = Repository.Get(id);
    ...
}