首页 > 解决方案 > 用于生成许多下拉列表的 HTML 辅助方法

问题描述

我有以下看法:

@model Entities.Models.Tournament

@using (Html.BeginForm("Index", "Game"))
{        
    <table>
        <tr>
            <td><label>Team</label></td>
            <td><label>Points Brought To Tournament</label></td>
        </tr>
        @{
            const int maxNumOfTeams = 8;
            for (int i = 0; i < maxNumOfTeams; i++)
            {
                <tr>
                    <td>@Html.DropDownList("SelectedTeams[" + i + "].TeamId", Model.Teams, "Please select:")</td>
                    <td>@Html.TextBox("SelectedTeams[" + i + "].Points", "", new { type = "number" })</td>
                </tr>
            }
        }
    </table>    
    <input type="submit" value="Create game" />
}

是否有一种更优雅/“最佳实践”的方式来生成 8 个下拉菜单,然后List<T>使用 HTTP Post 构建一个并将其发送到操作方法?

我现在这样做的方式似乎很混乱,因为我必须使用连接和i变量来构建下拉列表的 html ID 字符串。

这是模型:

public class Tournament
{
    //This is populated with teams from the DB and then used in the view to allow the user to select a team
    public IEnumerable<SelectListItem> Teams { get; set; } 

    //This represents the teams the user selected
    public List<TeamWithPointsBroughtForward> SelectedTeams { get; set; }
}

public class TeamWithPointsBroughtForward
{
    public int TeamId { get; set; }
    public int Points { get; set; }
}

这是控制器和操作方法:

public class GameController : Controller
{        
    public ActionResult Index(Tournament tournament)
    {            
        Game game = new Game();
        //TODO: set up the game object based on the tournament settings

        return View(game);
    }
}

标签: c#asp.netasp.net-mvcrazorasp.net-mvc-5

解决方案


推荐阅读