tags:

views:

237

answers:

1

I'm trying to write a simple extension method that allows me to select an item in an MVC SelectList by text rather than value.

This is what I came up with but although the item is set as selected while debuging, the returned SelectList has all it's items with selected = false.

Any ideas?

 public static SelectList SelectByText(this SelectList list, string TextValue)
        {
            foreach (var item in list)
            {
                if (item.Text == TextValue)
                {
                    item.Selected = true;
                }
            }
            return list;
        }
+2  A: 

It is not wise to trying to select item on his text instead of a value

anyway,it seems that you have more than one item that satisfies your if statement

to ensure that only one item will be selected you can put a break when you meet condition like this:

if(item.Text == TextValue)
{
  item.Selected = true;
  break;
}

cheers

Marko