简体   繁体   中英

Conditional background/font color in dropdownlist

Is this possible? I have the following in my cshtml (razor) MVC 4:

@Html.DropDownListFor(v => v.Medico, ((IEnumerable<SelectListItem>)ViewBag.Medicos), new { @class="span4"})

This is on controller, how I generate the list:

List<Medico> list = null;
Medico medico = null;
if (visitador != null){
    list = new List<Medico>(visitador.Medicos.OrderBy( m => m.Nombre));

    for (int i = 0; i < list.Count(); i++)
    {
        var item = list[i];
        if (i == 0 && medico == null) medico = list[i];
        medicosList.Add(new SelectListItem { Text = item.Nombre + " " + item.Apellido, Value = item.Id.ToString()});

I need to mark somehow in the dropdownlist which "Medico" meets X condition. How can I achieve it? I have a bool method to check the condition which can be called from controller, but after googling a lot I have no idea how to "mark" these.

Can't think of the top of my head how you could do it using a selectitem list and Html.DropDownList but you could easily do it in a different way

In your controller instead of what you have now simply only have the list because thats all you need

List<Medico> list = new List<Medico>(visitador.Medicos.OrderBy( m => m.Nombre));
** Edit **

foreach(var m in list)
{
  //check each one against your repository here and have something inside of Medico to tell you the result
}

and in your HTML you can easily create the dropdown list by yourself ( as long as the name properly is the same as the property name in your model which is Medico the binding will work )

<select id="Medico" name="Medico">
 @foreach(var medico in (List<Medico>)ViewBag.Medicos)
 {
   if(medico.something = "something")
      <option id="@medico.Apellido" value="@medico.Id" style="background-color: blue">@medico.Nombre</option>
   else if(medico.something ="something else")
      <option id="@medico.Apellido" value="@medico.Id" style="background-color: red">@medico.Nombre</option>
 }
</select>

Basically in the foreach loop you can check each of your medico variables against a condition and depending on that you can give it a different class or style as you want

combining code from here remove specific items from dropdown list using jquery and here Change the background color of dropdownlist JQuery

see if this will work for you

var $list = $("#myList"),
toColor= $();

for(var i = selectedItems.length; i--;) {
   toColor= toColor.add($list.find('option[value="' + selectedItems[i] + '"]'));
}
toColor.css(TextHighlightCss);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM