Anton Selin
Anton Selin

Reputation: 3642

MVC passing complex object to action

I have two actions in my controller when a user call one i need to redirect it to another one and pass a complex object :

first action :

public virtual ActionResult Index(string Id) {
            var input = new CustomInput();
            input.PaymentTypeId = Id;
            return RedirectToAction(MVC.Ops.SPS.Actions.Test(input));
        }

second action :

public virtual ActionResult Test(CustomInput input) {
            return View();
        }

The probelm is that the input arrives null at the second action. how can i solve it?

Upvotes: 0

Views: 4793

Answers (2)

Hossam Barakat
Hossam Barakat

Reputation: 1397

I want to make sure that you know that RedirectToAction creates new HTTP request so this create another GET and all you can pass is RouteValueDictionary object which is like having query string parameters which is list of key and value pairs of string. That said, You can't pass complex object with your way of code however the TempData solution mentioned by @kyleT will work.

My recommendation based on your code is to avoid having two actions and redirect from one another unless you are doing something more than what you have mentioned in your question. Or you can make your Test action accepting the id parameter the your Index action will contain only RedirectToAction passing the id as route parameter.

Edit: Also, If you have no primitive properties you can pass your object like the following (Thanks to @Stephen Muecke)

return RedirectToAction("Test",(input);

Upvotes: 0

Master Yoda
Master Yoda

Reputation: 4412

You can solve this using temp data to temporarily hold a value from which the second method retrieves that value.

public virtual ActionResult Index(string Id) 
{
    var input = new CustomInput();
    input.PaymentTypeId = Id;
    TempData["TheCustomData"] = input; //temp data, this only sticks around for one "postback"
    return RedirectToAction(MVC.Ops.SPS.Actions.Test());
}


public virtual ActionResult Test()
{
        CustomInput = TempData["TheCustomData"] as CustomInput;
        //now do what you want with Custom Input
         return View();

}

You can keep your tempData going so long as it is never null using the .keep() method like this,

    if (TempData["TheCustomData"] != null)
        TempData.Keep("TheCustomData");

Upvotes: 3

Related Questions