2011-06-10 105 views
1

我一直在處理與我能夠填充,但如果我回來編輯記錄,下拉列表不顯示所選值下拉列表.....ASP.Net MVC下拉列表中選擇價值

在控制器,

 var datacontext = new ServicesDataContext(); 
     var serviceToUpdate = datacontext.Mapings.First(m => m.CustomerServiceMappingID == id); 
     var qw = (from m in datacontext.Mapings 
        where id == m.CustomerServiceMappingID 
        select m.CustomerID).First(); 
     ViewData["CustomerID"] = qw; 
     int b = Convert.ToInt32(serviceToUpdate.ServiceID); 
     var a = datacontext.services.Select(arg => arg.ServiceID).ToList(); 
     ViewData["ServiceID"] = new SelectList(a,serviceToUpdate.ServiceID); 

鑑於:

@Html.DropDownListFor(model => model.ServiceID, ViewData["ServiceID"] as SelectList) 

serviceToUpdate,服務ID具有正確的值,但不知何故,當我嘗試編輯沒有返回所選值...相反下拉列表的第一個值只返回...

回答

0

我有同樣的問題。使用空對象模式,你有一個保留的ID和該項目的顯示名稱是「請選擇...」或類似的東西。在將模型傳遞給視圖之前,將空對象追加到集合的開頭。在回到路上的控制器中,測試它。如果該人沒有選擇任何內容,則可以將該屬性設置爲null。

這裏是我的問題:

DropDownListFor Not Displaying/Persisting Null for First Choice in List

你不應該有明確要麼喜歡你正在做使用視圖的數據。

+0

嘿,我正在從數據庫中得到結果..所以,你認爲null模式是可能的嗎? – 2011-06-10 06:40:20

+0

如果結果爲空,則將所選項目設置爲空對象 – 2011-06-10 06:42:19

+0

結果永遠不會爲空。所選值被提取並且正確無誤當我點擊編輯時它不顯示選定值 – 2011-06-10 06:43:55

0

守則控制器:

ViewBag.Services = new SelectList(a, "ServiceId", "@Servicename"); 
  • SERVICEID是代表在下拉列表中
  • @Servicename顯示的項目的鍵值屬性代表屬性表示要顯示的文本在下拉列表中查看的項目)

代碼:

@using(@BeginForm){ 
    SelectList services = Viewbag.Services; 
    @Html.DropDownListFor(model => model.ServiceID, services) 
} 
+0

是你肯定這個答案..? – 2011-06-16 16:00:27

+0

@Pushpendra_Kuntal爲什麼不呢? – Tobias 2011-06-27 08:41:51