-1

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!

  • I'm guessing you did not bother to check what happens when you use the code in the accepted answer (it will not bind to your model when you submit the form!). Refer [this answer](http://stackoverflow.com/questions/31174250/how-to-set-default-value-to-select-list-in-mvc-during-run-time/31174308#31174308) for how to do this correctly. And to understand why you cannot use a `foreach` loop, refer [this answer](http://stackoverflow.com/questions/30094047/html-table-to-ado-net-datatable/30094943#30094943) –  Mar 04 '16 at 03:21
  • @StephenMuecke Thanks for the suggestion. I realized that the answer wasn't perfect, but it was the hint and start I needed, and I was able to figure the rest out myself. – JoeFromAccounting Mar 04 '16 at 20:05
  • Therefore it should be up-voted (because its helpful), not accepted (which indicates to others that the answer works - when in fact it does not) –  Mar 05 '16 at 00:37

1 Answers1

1
foreach (MyModel item in Model)
{
    <td> 
        @Html.DropDownList("myList", typeList, item.type) 
    </td>
}
James Dev
  • 2,979
  • 1
  • 11
  • 16