0

I have problem with dropdown list for my model. I cant set default selected value. Here is my code. Select list definition:

var productGroups = db.sl_GrupaKh.AsNoTracking()
        .Where(g => g.kh__Kontrahent.Any())
        .Select(n => new {n.grk_Id, n.grk_Nazwa })
        .OrderBy(n => n.grk_Nazwa).ToList();
        productGroups.Add(new { grk_Id = 0, grk_Nazwa = "(" + Resources.Resources.NoneLabel + ")" });
        productGroups.Add(new { grk_Id = -1, grk_Nazwa = "(" + Resources.Resources.AnyLabel + ")" });

        var selectedItem = productGroups.SingleOrDefault(x=>x.grk_Id==selected);
        SelectList selectList = new SelectList(productGroups,"grk_Id","grk_Nazwa",selected);

grk_Id - int type, grk_Nazwa-string type, selected - int type I have watched that selected matches one of options value.

Now view code:

    @Html.DropDownListFor(m => m.customerMenu, Model.customerMenu,
new  {@class="myClass" })

And output:

<select class="dasdas" id="customerMenu" name="customerMenu">
<option value="2">Drogerie</option>
<option value="3">Fabryki</option>
<option value="4">Hurtownie</option>
<option value="5">Importerzy</option>
<option value="1">Podstawowa</option>
<option value="6">Sklepy</option>
<option value="0">(brak)</option>
<option value="-1">(dowolna)</option>
</select>

Im looking forward for any help. Thank You :)

Paulie
  • 121
  • 2
  • 14

2 Answers2

1

Instead of SelectList you can make use of List<SelectListItem> you only have to win from this, no more hardcoded strings, and you are sure that Selected item is true when you want.

var selectedItem = productGroups.SingleOrDefault(x=>x.grk_Id==selected);
List<SelectListItem> selectList = productGroups.Select(c => new SelectListItem
        {
            Text = c.grk_Nazwa,
            Value = c.grk_Id,
            Selected = selectedItem != null && selectedItem.grk_Id == c.grk_Id
        });

Note: if you can't change SelectList try this SO answer, this will help you to convert from List<SelectListItem> to SelectList.

Community
  • 1
  • 1
adricadar
  • 9,971
  • 5
  • 33
  • 46
0

I think here is a mistake

SelectList selectList = new SelectList(productGroups,"grk_Id","grk_Nazwa",selected);

This

var selectedItem = productGroups.SingleOrDefault(x=>x.grk_Id==selected);

must be changed to this

var selectedItem = productGroups.SingleOrDefault(x=>x.grk_Id==selected).grk_Id;

Maybe with NullReferenceCheck.

Barada
  • 252
  • 2
  • 10
  • @adricadar solution much better. – Barada Apr 15 '15 at 08:28
  • But i've used selectedItem just to see if the selected parameter doesnt point to null while debbuging. As you can see: SelectList selectList = new SelectList(productGroups,"grk_Id","grk_Nazwa",selected); there is selected parameter not selectedItem – Paulie Apr 15 '15 at 08:29