代码之家  ›  专栏  ›  技术社区  ›  Damovisa

如何在ASP.NET MVC编辑页面中绑定多个下拉列表?

  •  2
  • Damovisa  · 技术社区  · 16 年前

    我有一个viewmodel,它包含许多属性、一个SelectList和一系列子对象。

    public class RoundViewModel
    {
        public int RoundId { get; set; }
        public string RoundName { get; set; }
        public SelectList Teams { get; private set; }
        public List<GameViewModel> Games { get; set; }
    }
    
    public class GameViewModel
    {
        public int HomeTeamId { get; set; }
        public int AwayTeamId { get; set; }
        public DateTime GameTimeGMT { get; set; }
    }
    

    每轮可以有不同数量的游戏,我正在尝试绑定相同的游戏 Teams 选择我在页面上放置的每个下拉列表:

    <% using (Html.BeginForm()) {%>
    
        <fieldset>
            <legend>Fields</legend>
            <%= Html.HiddenFor(model => model.CodeId) %>
            <div class="editor-label">
                <%= Html.LabelFor(model => model.RoundNumber) %>
            </div>
            <div class="editor-field">
                <%= Html.TextBoxFor(model => model.RoundNumber) %>
                <%= Html.ValidationMessageFor(model => model.RoundNumber) %>
            </div>
    
            <div class="editor-label">
                <%= Html.LabelFor(model => model.RoundName) %>
            </div>
            <div class="editor-field">
                <%= Html.TextBoxFor(model => model.RoundName) %>
                <%= Html.ValidationMessageFor(model => model.RoundName) %>
            </div>
    
            <%     
            for (int i = 0; i < Model.Games.Count; i++)
            {
            %>
            <div class="editor-label">
                Game:
            </div>
            <div class="editor-field">
            <%= Html.DropDownList("Games[" + i + "].HomeTeamId", Model.Teams, "--No Game--", new { value = Model.Games[i].HomeTeamId })%> VS 
            <%= Html.DropDownList("Games[" + i + "].AwayTeamId", Model.Teams, "--No Game--", new { value = Model.Games[i].AwayTeamId })%>
    
                <%= Html.TextBox("Games[" + i + "].GameTimeGMT", Model.Games[i].GameTimeGMT, new { Class = "calendar", value = Model.Games[i].GameTimeGMT })%>
            </div>
            <% } %>
    
            <p>
                <input type="submit" value="Save" />
            </p>
        </fieldset>
    
    <% } %>
    

    类似的视图可以很好地用于创建操作,但我似乎无法在每个下拉列表中设置现有的选择。你可以看到我正在为每个游戏明确设置日期时间。

    new { value = Model.Games[i].HomeTeamId } line在该行上设置一个属性 <select> html元素,但显然这是行不通的。我曾考虑过设置另一个属性,并使用jQuery设置所选项目,但它感觉比现有代码更粗糙。

    我是MVC的新手,所以如果我做得不对,我肯定会感激的。有人能帮忙吗?

    1 回复  |  直到 12 年前
        1
  •  2
  •   David    16 年前

    如果查看SelectList对象的构造函数,则可以看到它将IEnumerable对象列表作为其源,并使用其他参数来设置数据和文本字段以及所选项。

    Html.DropDownList("Games[" + i + "].HomeTeamId", 
        new SelectList(Model.Teams, Model.Games[i].HomeTeamId));
    
    public class RoundViewModel
    {
        ....
        public IList<TeamObject> Teams { get; private set; }