DropDownListFor callback or if statement

In my MVC3 application, I have a drop down list. There I must show all the results, but some results must be disabled so that they are not selected. How can i do this?

This is what I have right now. It simply does not show players whose Disabled is set to true.

@Html.DropDownListFor(m => m.Position1, Model.SelectedTeam.TeamPlayers .Where(c => c.Player.Disabled == false) .OrderBy(t => t.Player.Lastname) .ToSelectList(m => m.FullName, m => m.PlayerId)) 

So, there is another way to show disabled players, but the result will be like this, and not just completely hide them:

 <select> <option>Player 1</option> <option disabled="disabled">Player 2</option> <option>Player 3</option> <option>Player 4</option> <option disabled="disabled">Player 5</option> <option>Player 6</option> </select> 

Is this possible with DropDownListFor?

+6
source share
1 answer

OK, here is the "hard way." :) Maybe someone will have a better idea.

First, you will need to distinguish between valid and disabled entries in the selection list, and the only way to do this is either value or text option . Say invalid values ​​will have the value value == "disabled" , otherwise this is a valid identifier:

 //Somewhere in the controller ... var list = yourViewModel.SelectedTeam.TeamPlayers.OrderBy(p => p.LastName).Select(new SelectListItem { Text = item.LastName, Value = item.Disabled ? "disabled" : item.PlayerId.ToString() }).ToList(); //pass it however you want, in the model or by ViewBag ViewBag.MyDropDownList = new SelectList(list, "Value", "Text"); 

And then in the view

 @Html.DropDownListFor(model => model.Position1, ViewBag.MyDropDownList as SelectList); 
 $(document).ready(function() { $(#"Position1 option[value=\"disabled\"]").prop("disabled",true); }); 
+2
source

Source: https://habr.com/ru/post/918645/


All Articles