2013-10-31 98 views
2

我使用MVC4,mvc4動態dropdownlistfor綁定選定值

在控制器側我有2個表:

1>CarrierList: - 它包含交通數據列表。

2>TransPortationModeList: - 它包含所選運輸數據的ID &它來自數據庫。

現在,在編輯模式下,我必須首先將dropdownlist與「CarrierList」記錄綁定。 並且還選擇該列表的哪個id(值)應該來自「TransPortationModeList」的屬性。

對於我的看法代碼:

@foreach (var Data in Model.TransPortationModeList) 
       { 

    @Html.DropDownListFor(lm => lm.TransPortationModeList[Model.TransPortationModeList.IndexOf(Data)].TransModeId, Model.CarrierList.Select(c => new SelectListItem { Text = c.TransportationName + "-" + c.TransportationModelID, Value = c.TransportationModelID }), TransPortationModeList[Model.TransPortationModeList.IndexOf(Data)].TransModeId, new { @class = "form-control" }) 

} 

這裏:TransPortationModeList [Model.TransPortationModeList.IndexOf(數據)] TransModeId這是給我的ID。

now,by this code.i am not bind bind dropdownlist for Selected record。

請讓我知道。我在這裏錯過了什麼?

謝謝。

+0

你的'Data'屬性是如何初始化的?此外,在您收集「SelectListItem」之後,您不應該指定'TransModeId',因爲所選值應該由第一個參數提供('lm => lm.TransPortationModeList [Model.TransPortationModeList.IndexOf(Data)]。TransModeId ') –

+0

@RédaMattar - 用於我正在使用foreach的數據。讓我再次更新我的問題。 – Kvadiyatar

回答

-1

它可以是一個for循環更簡潔,因爲你避免IndexOf用法:

@for(int index = 0; index < Model.TransPortationModeList.Count; index++) 
{ 
    @Html.DropDownListFor(lm => lm.TransPortationModeList[index].TransModeId, 
           Model.CarrierList.Select(c => new SelectListItem { Text = c.TransportationName + "-" + c.TransportationModelID, Value = c.TransportationModelID }), 
           new { @class = "form-control" }) 

} 

第一個參數將包含選定的值。

+0

它只會返回記錄中沒有SELECTED ID值的第一個值... – Kvadiyatar