Search code examples
c#asp.net-mvcrazor

Can't pass a parameter when redirecting to view


I am new to ASP.NET MVC, I am writing my first project and usually I get a lot of problems but I always find a solution to solve them.

But now, I have no idea why when I'm trying to redirect to my action named "All" with parameter "query" and "page". I successfully pass the "page" parameter but not the "query", it is always have 0 items.

In Search action, the result is calculated properly and

await flightService.AllFlightsFilter

returns results just fine, but I can't pass it to All action. When I debug, the query parameter in action All is empty.

    [HttpGet]
    [AllowAnonymous]
    public async Task<IActionResult> All(List<FlightViewModel> query, int page=1)
    {
        var pagedFlights = query.ToPagedList(page, pageSize);

        return View(pagedFlights);
    }

    [HttpPost]        
    public async Task<IActionResult> Search(AllFlightsQueryModel query)
    {
        var result = await flightService.AllFlightsFilter(
            query.Sorting,
            query.SearchDate,
            query.ArrivalAirportId,
            query.DepartureAirportId                
            );
        //query.Flights = result.ToPagedList(query.page, pageSize);

        return RedirectToAction("All", new { result, page=1});
    }

I thought maybe the All action expects to return exactly the same type so I changed it from generic type to return a list from flightService.AllFlightsFilter and to pass that list to the All action - but it didn't work.


Solution

  • This is a known issue of passing compound objects when calling the RedirectToAction() method. The URL just doesn't have enough place for lot of parameters. Therefore use the TempData:

    TempData["list"] = result;
    return RedirectToAction("All", new { page=1});
    

    And in the All() action method:

    public async Task<IActionResult> All(int page=1)
    {
        if (TempData["list"] is List<FlightViewModel> list)
        {
            var pagedFlights = list.ToPagedList(page, pageSize);
            return View(pagedFlights);
        }
        return View("Index");
    }