【问题标题】:Why is there no option selected in the drop down list?为什么下拉列表中没有选择选项?
【发布时间】:2010-12-08 21:13:47
【问题描述】:

我很困惑为什么选择列表中的相应选项没有被选中。 当我单步执行循环时,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");

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-2 drop-down-menu selectlist


    【解决方案1】:

    好的,那我建议你把 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>
    <% } %>
    

    【讨论】:

    • 我希望是这样。抱歉有点混乱(我更新了代码),但我肯定得到了DisciplineId,这是一个简单的string 变量。
    • 更新了答案..希望对您有所帮助。
    • 完美运行,但希望我知道为什么它不快乐。我什至没有想过要制作一个方法,我必须记住这一点。感谢您的帮助!
    • 我意识到前面的示例为所有下拉列表提供了相同的 ID“item_DisciplineId”,因此它不能用于 POST 场景 b/c TeamMembers 不会自动填充 - 请考虑使用修订版。顺便说一句 - 您还可以更进一步并使用模板视图实现 Html.EditorFor 但这是另一回事。
    猜你喜欢
    • 1970-01-01
    • 2017-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多