1

how to set a default selected value if my value from my setting is the same as it is from my select list

as with

         @{
       var pstSelect = (SelectList)ViewData["Printerlist"];
        pstSelect.ForEach(o =>
        {
        if (o.Value== setting.printerName )
        {
        o.Selected = true;
        }
        });
        }
        @Html.DropDownListFor(m => setting.printerName , pstSelect)

i gets

CS1061: 'SelectList' does not contain a definition for 'ForEach' and no extension method 'ForEach' accepting a first argument of type 'SelectList' could be found (are you missing a using directive or an assembly reference?)

so how do i do this probably

omini data
  • 407
  • 7
  • 29
  • Its the value of `printerName` that determines what is selected. Delete your `ForEach()` - attempting to set the `Selected` property is pointless since its ignored anyway –  Apr 13 '18 at 10:24

1 Answers1

2

You could convert/create a List of objects that matches your dropdown and then do a loop on the objects in the list and if the objects value matches your setting.printerName set it to selected

<select >
                                        @foreach (var child in MyData)
                                        {
                                            if (child.Value == setting.printerName)
                                            {
                                                selected = "selected='selected'";
                                            }
                                            else
                                            {
                                                selected = "";
                                            }
                                            <option @selected value="@child.Value">@child.Text</option>
                                        }
                                    </select>
Bombebak
  • 114
  • 2
  • 11
  • how exactly do you call that function to the @Html.DropDownListFor? – omini data Apr 13 '18 at 10:48
  • 1
    You don't. @Html.DropDownListFor is a razor helper than generates a myself and used the data from your ViewData into a list instead of a selectList. – Bombebak Apr 13 '18 at 11:17