用于生成许多下拉列表的HTML帮助器方法

时间:2019-01-15 23:52:05

标签: c# asp.net asp.net-mvc razor asp.net-mvc-5

我有以下观点:

@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);
    }
}

0 个答案:

没有答案