Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DropDownListFor callback or if statement

In my MVC3 application i have a dropdown list. In there i have to show all the results, but some results must be disabled, so that they are not selectable. How can i do that?

This is what i have right now. It simply doesn't show the players that have Disabled 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 is there another way to also show the Disabled players, but that the output would be like this, instead of just hiding them completely:

<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 that possible with a DropDownListFor?

like image 356
w00 Avatar asked Jun 21 '12 10:06

w00


1 Answers

OK, here's the 'hard way' of doing it. :) Maybe someone else will have a better idea.

First, you'd need to differ between valid and disabled entries on the select list - and only way to do it is either by value or text of the option. Let's say the invalid values will have the value == "disabled", otherwise it's a valid ID:

//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);
});
like image 58
Patryk Ćwiek Avatar answered Nov 13 '22 19:11

Patryk Ćwiek