Accessing properties of object in SelectList in C#

Viewed 187

I'm a newbie here. I'm trying to create a dropdown list (SelectList) which would display the location of shops in my ASP.NET MVC application.

The Shop class has a Location property which in turn has a Name property:

public class Shop
{
    public int Id { get; set; }
    public Location Location { get; set; }
}

public class Location
{
    public int Id { get; set; }
    public string Name { get; set; }
}

The Name property is a string.

I tried to use this code:

var shops = _applicationDbContext.Shops
                                 .Include(x => x.Location).ToList();

var mwc = new Create
              {
                   ShopSL = new SelectList(shops, nameof(Shop.Id), nameof(Shop.Location.Name)) 
              };

But I get an error:

Object reference not set to an instance of an object

If I remove the Shop.Location.Name and change it to Shop.Location only, the dropdown list displays the object instead, something like Namespace.Data.Location.

I would like the dropdown list to be able to display the name of the location.

Could someone point me to the right direction please? Thank you.

1 Answers

try this

var shops = _applicationDbContext.Shops
                    .Select (i=> new 
                    {
                     Id=i.Id
                     Name=i.Location.Name
                     }).ToList();

var mwc = new Create
              {
                   ShopSL = new SelectList(shops,"Id","Name") ;
              };

Related