Search code examples
c#asp.net-corecomboboxselectlist

get id of Selected Tag


how can i give Id of my selected tag in c# this is my code:

Options = new SelectList(_db.CityUserTable, nameof(CityUserTable.CityID), nameof(CityUserTable.CityName));
            Options.First(x => x.Value == user.CityID.ToString()).Selected = true;

Solution

  • You have it backwards. You're setting the property Selected true where CityId matches. Instead you need to get the Value (Assuming value contains the CityId) where Selected is true.

    Options.FirstOrDefault(x => x.Selected)?.Value
    

    Use ? after FirstOrDefault to ensure a selected match was found before accessing Value.