0

in which way I can pass data from one controller to another?

I have this action CheckReservation in HomeController:

public class HomeController : Controller
{

    public readonly ICarRepository _repository;

    public HomeController(ICarRepository repository)
    {
        _repository = repository;
    }

    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public IActionResult CheckReservation(Reservation reservation)
    {
        List<Car> availableCars = _repository.GetAvailableCars.Where(c => c.Location == reservation.PickUpLocation && c.Available);

        return RedirectToAction("List", "Car", availableCars);

    }
}

And I have this action List in CarController:

public class CarController : Controller
{
    private readonly ICarRepository _repository;

    public CarController(ICarRepository repository)
    {
        _repository = repository;
    }

    [HttpPost]
    public IActionResult List(List<Car> cars = null)
    {
        if(ModelState.IsValid)
        {
            if(cars == null)
            {
                var carsListViewModel = new CarsListViewModel
                {
                    Cars = _repository.GetAllCars
                };
                return View(carsListViewModel);
            }
            else
            {
                return View(cars);
            }
        }

        return NotFound();

    }

    public IActionResult Detail(int id)
    {
        var car = _repository.GetAllCars.FirstOrDefault(c => c.Id == id);

        return View(car);

    }
}

I tried on this way but I only getting cars list without any elements. What is correct way to pass data between controllers?

Edit: Found solution here: link

TJacken
  • 354
  • 3
  • 12

1 Answers1

0

You can use the TempData to transfer the data.

TempData["Key"] = dataObject;

And accessing the same dataObject in another Controller

Object data = TempData["Key"] as Object; 

You can use tempdata on next request using Keep() method also.

vvvvv
  • 25,404
  • 19
  • 49
  • 81