tags:

views:

1762

answers:

3

I have a SelectList that I first check for a selected value != null and then want to use this selectedvalue in a where clause for a filter. Like so:

if(searchBag.Qualities.SelectedValue != null){
    ListItem selected = (ListItem)searchBag.Qualities.SelectedValue;
}

I made the cast in a seperate useless line to pinpoint the problem. This gives me a

Unable to cast object of type 'WhereListIterator`1[System.Web.Mvc.ListItem]' to type 'System.Web.Mvc.ListItem'.

Weuh?

--EDIT--
It was indeed because multiple selections were made. This was because on creation I set the selected value to theItems.Where(i=>i.someCriterea) and I forgot to put .FirstOrDefault() at the end. Ending up in the possibility of multiple answers. Since it was an IEnumerable, it was a lazy list and hence the WhereListIterator I guess. I solved it by simple putting FirstOrDefault at the end.

A: 

I assume the SelectList lets you select more than 1 item?

So SelectedValue is probably a list? Not 1 listitem.

Cast it to:

 WhereListIterator<ListItem> selected = (WhereListIterator<ListItem>)searchBag.Qualities.SelectedValue;

instead and see what properties you have there.

Wolf5
A: 

SelectedValue is not a ListItem, it's the value of the selected list item. So given this:

var selectList = new SelectList(companiesList, "Id", "Name", companiesList[3]);

selectList.SelectedValue will equal companiesList[3].Id. If you want the actual list item you can do something like this:

ListItem selected = selectList.GetListItems().Where(x => x.Value == selectList.SelectedValue.ToString())

Just curious, why do you want the selected list item?

Tim Scott
A: 

Its already been explained, but here's another suggestion as to how to get what you're looking for:

if(searchBag.Qualities.SelectedValue != null){
    ListItem selected = (ListItem)searchBag.Qualities.SelectedValue.FirstOrDefault();
}
Will