2010-12-08 52 views
2

我很困惑,爲什麼選擇列表中的相應選項沒有被選中。 當我通過循環,item.DisciplineId = 2,但學校沒有被選中(「選擇」仍然是)。有什麼建議麼 ?爲什麼在下拉列表中沒有選擇任何選項?

查看

<% foreach (var item in Model.TeamMembers) 
{ %> 
<tr> 
    <td> 
     <%: Html.DropDownListFor(m => item.DisciplineId, Model.MemberDisciplines, "Choose") %> 
    </td> 
</tr> 
<% } %> 

視圖模型

public SelectList MemberDisciplines { get; set; } 
public IEnumerable<TeamMember> TeamMembers { get; set; }//Set from the model 

MemberDisciplines = new SelectList(new[] { 
       new SelectListItem{ Text = "Technical", Value = "1"}, 
       new SelectListItem{ Text = "School", Value = "2"}, 
       new SelectListItem{ Text = "Health", Value = "3"} 
      }, "Value", "Text"); 

回答

2

好吧,我會那麼建議你MemberDisciplines財產轉換成一個方法具有以下內容:

public SelectList GetMemberDisciplines(object selectedValue) 
{ 
    return new SelectList(new[] { 
     new SelectListItem{ Text = "Technical", Value = "1"}, 
     new SelectListItem{ Text = "School", Value = "2"}, 
     new SelectListItem{ Text = "Health", Value = "3"} 
    }, "Value", "Text", selectedValue); 
} 

然後你在你的DropDownListFor中調用它如下:

<% for (int i = 0; i < Model.TeamMembers.Count; i++) { %> 
    <tr> 
     <td> 
      <%: Html.DropDownListFor(m => Model.TeamMembers[i].DisciplineId, Model.GetMemberDisciplines(Model.TeamMembers[i].DisciplineId), "Choose..")%> 
     </td> 
    </tr> 
<% } %> 
+0

我希望是這樣。對不起,我有點困惑(我更新了代碼),但我肯定會得到'DisciplineId`,它是一個簡單的`string`變量。 – MisterIsaak 2010-12-08 23:24:55

相關問題