I have a viewmodel that contains a number of properties, a SelectList, and an array of child objects.
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; }
}
There can be a variable number of games per round, and I'm trying to bind the same Teams
SelectList to each dropdown I put on the page:
<% 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>
<% } %>
A similar view works fine for the Create operation, but I can't seem to set the existing selection in each of the dropdown lists. You can see I'm explicitly setting the datetime for each game.
The new { value = Model.Games[i].HomeTeamId }
line sets an attribute on the <select>
html element, but obviously this isn't going to work. I thought about setting another attribute and using jQuery to set the selected item, but it feels even more hacky than the existing code.
I'm fairly new to MVC, so I can definitely appreciate if I'm doing this all the wrong way. Can anyone assist?