How to get Id from SelectList.Items[0].Id?

Volk Volk 571 Reputation points


It seems to be a simple question, but I searched all the internets and could not find an answer.
I just need to get "Id" property here. I don't know how to do it.
I tried it in different ways, it doesn't work.



A set of technologies in the .NET Framework for building web applications and XML web services.
4,141 questions
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 47,716 Reputation points

    SelectList is a generic object collection. It appears that you're populating a SelectList with your object types and want to default the new likes to the first one. In that case honestly just use the raw data.

       var objectTypes = _db.ObjectTypes.ToList();  
       var defaultObjectType = objectTypes.FirstOrDefault();  
       likes.ObjectTypeId = defaultObjectType.Id ?? 0;  

    I don't know why you're creating a SelectList here because it appears you're just updating your database which has nothing to do with the UI. So your code doesn't need this object. But for completeness if you had a SelectList and needed to get back to the original object then you'd need to do a cast.

       var selectedObjectType = selectList.SelectedValue as ObjectType;  
       likes.ObjectTypeId = selectedObjectType?.Id ?? 0;  

    Finally note that I hope you're not trying to retrieve the object type selected by the end user as part of your UI as the code you posted wouldn't work as you're creating a brand new select list in this code. To get what the user selected in your UI you need to use model binding like MVC normally uses.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful