0

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jakxna360
  • 857
  • 2
  • 9
  • 31
  • 1
    Does this answer your question? [How to pass IEnumerable list to controller in MVC including checkbox state?](https://stackoverflow.com/questions/17037858/how-to-pass-ienumerable-list-to-controller-in-mvc-including-checkbox-state) – Guruprasad J Rao Feb 01 '20 at 08:04
  • Sorry, It does not, I added the Model and will add the Razor code to make the question clearer. – Jakxna360 Feb 01 '20 at 08:07
  • https://www.learnrazorpages.com/razor-pages/model-binding – Denis Kucherov Feb 01 '20 at 08:18
  • You are sending `IEnumerable` to the view and expecting `@model Dealership.Domain.DatabaseContext` in the view? How would that be possible? – Guruprasad J Rao Feb 01 '20 at 08:21
  • This code is what was scaffolded... please let me know if this change and what to change it to. As stated I am new to Razor and not sure if scaffolding this is the way to go. – Jakxna360 Feb 01 '20 at 08:27

1 Answers1

0

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jakxna360
  • 857
  • 2
  • 9
  • 31