0

What would be the best approach to have multiple options when using a ViewData for a dropdown list. Something like this enter image description here

I am using: ViewData["LocationId"] = new SelectList(_context.Location, "LocationId", "Address", employees.LocationId); and it is only showing Address but I need it to : City Address City, State, Postal

In the front end I am calling it like so: <select asp-for="LocationId" asp-items="ViewBag.LocationId">

Can this be done using ViewData and selectList?

Thank you!

LinkedListT
  • 681
  • 8
  • 24

1 Answers1

2

Simply change to

ViewBag.LocationId = new SelectList(_context.Location, "LocationId", "Address", employees.LocationId);

Or if you really want to use ViewData

@{
    ...
    var items = ViewData["LocationId"] as IEnumerable<Microsoft.AspNetCore.Mvc.Rendering.SelectListItem>;
}

<select asp-for="LocationId" asp-items=@items></select>

I recommend reading What's the difference between ViewData and ViewBag?

But this is not really the recommended way to populate your view. You should use ViewModel instead, which allows you to specifically define your view requirements. Here is an example with ViewModel: MVC6 Dropdownlist of Countries

obl
  • 1,799
  • 12
  • 38