Ali Umair
Ali Umair

Reputation: 1424

Pass complex object in RedirectToAction MVC

I know this question has been asked several times and answered, but none of the solutions are working for me.

This is my ViewModel:

public class FlightSearchResults
{
    public FlightSearch SearchModel { get; set; }
    public List<vwLowFareSearchResults> SearchResults { get; set; }
    public string TestString { get; set; }
    public DateTime TestDate { get; set; }
}

I am using a RedirectToAction like this:

FlightSearchResults flightSearchResults = new FlightSearchResults();
flightSearchResults.SearchModel = model;
flightSearchResults.SearchResults = flights;
flightSearchResults.TestDate = DateTime.Now.AddDays(-2);
flightSearchResults.TestString = "Just Testing . . .";
return RedirectToAction("index", "flights", flightSearchResults);

I am only getting this List<vwLowFareSearchResults> SearchResults property in my flights index, none of the others are having values assigned. I have tried several variations from some threads on StackOverFlow like:

return RedirectToAction("index", "flights", new { SearchResults = flights, SearchModel = model });
return RedirectToAction("Result", "Dialog", new RouteValueDictionary(flightSearchResults));

I can return the view like this:

return View("~/Views/Flights/Index.cshtml", flightSearchResults);

but this is not a good solution as the url is not updated. I am modifying some older projects and it's mess of using Session and Viewbag.

I need to simplify and the pattern of view and controller communication of data in the previous code is a mess. Is it possible to do this without using the ViewData or Viewbag in a simple RedirectToAction.

Any kind of help in achieving this will be great as I am new to MVC.

Upvotes: 3

Views: 2199

Answers (1)

cometbill
cometbill

Reputation: 1619

Here is an approach I used recently. Try:-

        ... Previous code omitted.
        //In your controller action, save the data to TempData...
        TempData["FlightSearchResults"] = FlightSearchResults;

        return RedirectToAction("flights");
    }

    public ActionResult flights()
    {
        FlightSearchResults flightResults = TempData["FlightSearchResults"];

        return View(flightResults);
    }

I actually used NewtonSoft to serialise the objects to a string, and then back again in the target action. So you might want to try something like ...

using Newtonsoft.Json;
...
...

        ... Previous code omitted.
        //In your controller action, save the data to TempData...
        TempData["FlightSearchResults"] = JsonConvert.SerializeObject(FlightSearchResults);

        return RedirectToAction("flights");
    }

    public ActionResult flights()
    {
        string storedResults = TempData["FlightSearchResults"].ToString();

        FlightSearchResults flightResults = JsonConvert.DeserializeObject<FlightSearchResults>(storedResults);

        return View(flightResults);
    }

Upvotes: 1

Related Questions