I have a gender select field (--Select--, Male, Female) and I\'m populating that in my controller. When the page loads, I want the gender that is selected in the model pm.
After searching myself for answer to this problem - I had some hints along the way but this is the resulting solution. It is an extension Method. I am using MVC 5 C# 4.52 is the target. The code below sets the Selection to the First Item in the List because that is what I needed, you might desire simply to pass a string and skip enumerating - but I also wanted to make sure I had something returned to my SelectList from the DB)
Extension Method:
public static class SelectListextensions
{
public static System.Web.Mvc.SelectList SetSelectedValue
(this System.Web.Mvc.SelectList list, string value)
{
if (value != null)
{
var selected = list.Where(x => x.Text == value).FirstOrDefault();
selected.Selected = true;
}
return list;
}
}
And for those who like the complete low down (like me) here is the usage. The object Category has a field defined as Name - this is the field that will show up as Text in the drop down. You can see that test for the Text property in the code above.
Example Code:
SelectList categorylist = new SelectList(dbContext.Categories, "Id", "Name");
SetSelectedItemValue(categorylist);
select list function:
private SelectList SetSelectedItemValue(SelectList source)
{
Category category = new Category();
SelectListItem firstItem = new SelectListItem();
int selectListCount = -1;
if (source != null && source.Items != null)
{
System.Collections.IEnumerator cenum = source.Items.GetEnumerator();
while (cenum.MoveNext())
{
if (selectListCount == -1)
{
selectListCount = 0;
}
selectListCount += 1;
category = (Category)cenum.Current;
source.SetSelectedValue(category.Name);
break;
}
if (selectListCount > 0)
{
foreach (SelectListItem item in source.Items)
{
if (item.Value == cenum.Current.ToString())
{
item.Selected = true;
break;
}
}
}
}
return source;
}
You can make this a Generic All Inclusive function / Extension - but it is working as is for me.