我无法使用下面的简单代码获取下拉列表中的选定值 -
<select class="form-control" id="team-name" name="gameTypes">
@{long selectedOption = @ViewBag.HomeTeamId;}
@foreach (var item in Model.teams)
{
<option value="@item.TeamId" data-logo="@item.LogoURL" selected="@(selectedOption == @item.TeamId ? "selected" : "")">@item.FullName</option>
}
</select>
答案 0 :(得分:0)
我会这样做:
编写您的方法以在List<SelectListItem>
中获取所需的团队,然后在您的控制器中将值放入ViewBag(ViewBag.Teams = GetTeams();
)
例如:
[NonAction]
private List<SelectListItem> GetTeams()
{
IEnumerable<Team> teams = new List<Team>();
//fill the teams here from the DB
return teams.Select(team => new SelectListItem
{
Text = team.TeamName, //here you can select the property that you want to show as text in the dropdown
Value = team.ID.ToString()
}).ToList();
}
在您看来,检索
@{
List<SelectListItem> teams = ViewBag.Teams as List<SelectListItem>;
}
这里定义你的下拉列表并将团队作为数据源传递:
<div class="col-md-6 form-group">
@Html.LabelFor(model => model.TeamId, htmlAttributes: new { @class = "control-label" })
@Html.DropDownListFor(model => model.TeamId, teams, "Select a team", new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.TeamId, "", new { @class = "text-danger" })
</div>