Warm tip: This article is reproduced from stackoverflow.com, please click
asp.net-mvc c# razor razor-pages

Pass IEnumberable to View and Display It

发布于 2020-04-09 22:53:08

I have an Entity Class Owners that requires an associated class Cars to be linked with it:

    [Key]
    public int Id { get; set; }

    [Required]
    [MaxLength(32)]
    public string Name{ get; set; }

    [Required]
    public Cars AssociatedCar { get; set; }

The model I am using within my Razor page is my Owner:

@model Dealership.Domain.DatabaseContext

I'm using the scaffolded Razor pages as a base but they did not create a dropdown to choose a car to be linked with an owner. I have been able to get the selection view on my end using a private enumerable class within my controller:

    private IEnumerable<SelectListItem> GetAllCars()
    {
        var Cars = _carData.GetAllCars().Result;

        var List = Cars.Select(x => new SelectListItem { Value = x.Id.ToString(), Text = x.Name });

        return new SelectList(List, "Value", "Text");
    }

I then have it set within the scaffolded get controller:

    // GET: Buttons/Create
    public IActionResult Create()
    {
        var cars = GetAllCars();
        return View(cars);
    }

My question is how to I get the cars to show up onto a page through the variable? If it can't be done is there another way to add the Cars to the View? I am very new to Razor and unsure if it's possible using the scaffolded pages.

Questioner
Jakxna360
Viewed
51
Jakxna360 2020-02-02 20:58

After researching and learning more about Razor, I figured the easiest way to accomplish this was to create a viewmodel containing an IEnumberator<Cars>, a SelectedItem SelectedCar and OwnerModel Car. I then initialized the new viewmodel in the controller and was able to pass along the data.