我有一个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
SelectList绑定到我放在页面上的每个下拉列表中:
<% 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>
<% } %>
类似的视图适用于Create操作,但我似乎无法在每个下拉列表中设置现有选择。您可以看到我明确设置了每个游戏的日期时间。
new { value = Model.Games[i].HomeTeamId }
行在<select>
html元素上设置了一个属性,但显然这不起作用。我考虑过设置另一个属性并使用jQuery设置所选项目,但感觉比现有代码更加黑客。
我对MVC很新,所以如果我这样做的话,我肯定会感激不尽。有人可以帮忙吗?
答案 0 :(得分:2)
如果您看一下SelectList对象的构造函数,那么您可以看到它将IEnumerable对象列表作为其源和其他参数来设置数据和文本字段以及所选项目。
您的View模型存储SelectList而不是说团队列表是否有任何特殊原因?然后你就可以了
Html.DropDownList("Games[" + i + "].HomeTeamId",
new SelectList(Model.Teams, Model.Games[i].HomeTeamId));
public class RoundViewModel
{
....
public IList<TeamObject> Teams { get; private set; }