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 :)

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

@adricadar solution much better.
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.