asp.netasp.net-mvcobjectnerddinner

ASP.NET MVC: How to transfer more than one object to View method?


I finished NerdDinner tutorial and now I'm playing a bit with project. Index page shows all upcoming dinners:

    public ActionResult Index()
    {
        var dinners = dinnerRepository.FindUpComingDinners().ToList();
        return View(dinners);
    }

In DinnerRepository class I have method FindAllDinners and I would like to add to above Index method number of all dinners, something like this:

    public ActionResult Index()
    {
        var dinners = dinnerRepository.FindUpComingDinners().ToList();
        var numberOfAllDinners = dinnerRepository.FindAllDinners().Count();
        return View(dinners, numberOfAllDinners);
    }

Of course, this doesn't work. As I'm pretty new to OOP I would need help with this one.

Thanks,
Ile


Solution

  • Create view model:

    public class DinnerViewModel
    {
        public List<Dinner> Dinners { get; set; }
        public int NumberOfAllDinners { get; set; }
    }
    
    public ActionResult Index()
    {
        var dinners = dinnerRepository.FindUpComingDinners().ToList();
        var numberOfAllDinners = dinnerRepository.FindAllDinners().Count();
        return View(new DinnerViewModel { Dinners = dinners, NumberOfAllDinners = numberOfAllDinners } );
    }