I'm trying to set the default value of a select list using a corresponding value from my model. Let's say my model contains two fields, and ID and a Type. I have a TypeList, which contains a Type as a value, and the Type & Description as the text.
My view will be iterating through the Model for each object to display in a table, and for the "Type" column, I want to be able to display the TypeList dropdown menu. Most objects have a currently assigned type, so I want to be able to set the TypeList to show that specific type as the default.
This is what I have so far. For my model:
public class MyModel
{
public string ID;
public string type;
}
And in my view:
List<SelectListItem> typeList = ViewBag.TypeList ?? new List<SelectListItem>();
...
foreach ( MyModel item in Model)
{
<td>
@Html.DropDownListFor(m=>m.Where(n=>n.ID == item.ID).FirstOrDefault().type, typeList)
</td>
}
I believe there is something wrong with the way I'm building the dropdown list. Any help/suggestions would be greatly appreciated. Thank you!