Search code examples
c#asp.net-mvcmodelrazorengineselectlistitem

Adding an object from another class to SelectListItem?


Im wondering how SelectListItem works, kinda new at this. Been searching the net for a tutorial but nothing i could find made anny sense to me.

I have a controller and a method that returns a List of objects. I also have a ListModel class that has a List of SelectListItem wich is implemented in a @html.DropDownList in the View. Im trying to add the method from the controller to the SelectListItem-List but it wont work because List<MyClass> cannot be converted to List<SelectListItem>. However if i change List<MyClass> to List<SelectListItem> some values vill be selectable in the @html.DropDownList but i don't want to Display the values, i want to be able to select the method from the controller and then the method runs and returns the result.

The main idea is that when the end user select the item in the DropDownList the Method in the controller will run and display the data.

Would very much appreciate some input on this subject.

Thank you


Solution

  • try like this

    List<MyClass> class = new List<MyClass>();
    //populate class  here
    
    //put the objects in selectlist itme list, can filter if want specific element
    List<SelectListItem> list = class.Select(new SelectListItem{value = x.Valueprop, Text = x.textProp});