2015-04-15 80 views
0

我的模型下拉列表有問題。我不能設置默認選定的值。這是我的代碼。 選擇列表定義:MVC .NET DropdownList選定的值

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 - 整型,grk_Nazwa字符串類型,選擇 - 整型 我已經觀看了選擇匹配的期權價值之一。

現在查看代碼:

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

輸出:

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

林期待的任何幫助。謝謝:)

回答

1

相反的SelectList你可以利用的List<SelectListItem>你只需要從這場比賽的勝利,沒有更多的硬編碼字符串,並且你確信Selected產品true當你想要的。

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 
     }); 

注:如果你不能改變SelectList試試這個SO answer,這將幫助你轉換從List<SelectListItem>SelectList

+0

我會嘗試。謝謝。 :) – Paulie

+0

它已經奏效!非常感謝你。 – Paulie

0

我覺得這裏是一個錯誤

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

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

必須改變這種

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

可能。

+0

@adricadar解決方案好多了。 – Barada

+0

但我已經使用selectedItem只是爲了查看選中的參數是否在debbuging時不指向null。您可以看到:SelectList selectList = new SelectList(productGroups,「grk_Id」,「grk_Nazwa」,selected);有選擇的參數沒有selectedItem – Paulie