c# - ASP.NET MVC: DropDownListFor doesn't select any option -


I have to pop the drop down list in an asp.net MVC view.

  & lt;% = Html.DropDownListFor (model = & gt; model. Bike, model bike. Select (x = & gt; new SelectListItem {text = x.Name, Value = Url.Action ("Details", "Bike" new {bikeId = x.id}), selected = x.ID == Model.ID,}))% & gt; By debuging it, I can see that the  selected  property is set to  true  when it should be. But when the scene is provided, no option is selected from the list. 

Any thoughts?

I know that this can be done with another overload of DropDownListFor , but I really have to work on this version.

Your selected value does not work, because you are using the URL as an option value but Try Model.ID in the Selected section

like this:

  & lt;% = html DropDownListFor (model = & gt; model. Bike, new selection list (model box, "id", "name", model.id))% & gt;  

"ID" indicates the property that will be used as the option value, while "name" that property Point to the option label which will be used.

If you want to preserve the Url.Action you can try:

  & lt;% = Html.DropDownListFor ( Model = Gt; & gt; new {id = x.Id, name = Url.Action ("description", "bike", new {bikeId = x.ID})}), "id", "name", model .ID))% & gt;  

You will see that I have renamed the name and the ID because it seemed more logical to use the Model ID as the ideal ID.

Update:

The reason for this does not work because you are bound to IEnumerable dropdown list For assistant). When you are using the same model.bikes collection, it should be a scalar property:

   New selectionlight item {text = x.Name, value = url.action ("description", "bike", new {bikeId = x.ID} ), Selected = x.ID == Model.ID,})))%>  

The option values ​​are incorrect as my comment about not using the URL.


Comments

Popular posts from this blog

c# - sqlDecimal to decimal clr stored procedure Unable to cast object of type 'System.Data.SqlTypes.SqlDecimal' to type 'System.IConvertible' -

Calling GetGUIThreadInfo from Outlook VBA -

Obfuscating Python code? -