2
我有一个viewmodel包含一些属性,一个SelectList和一个子对象数组。如何在ASP.NET MVC Edit Page中绑定多个下拉列表?
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>
<% } %>
了类似的看法工作正常为创建操作,但我似乎无法设置每个下拉列表中的现有选择。你可以看到我明确地设置了每场比赛的日期时间。
new { value = Model.Games[i].HomeTeamId }
行在<select>
html元素上设置了一个属性,但显然这不起作用。我想过设置另一个属性,并使用jQuery来设置所选项目,但感觉比现有代码更加黑客。
我对MVC相当陌生,所以我可以肯定的是,如果我这样做是错误的。任何人都可以协助
太棒了,这个建议做到了。老实说,我使用的是SelectList,因为这是我遇到的大多数简单例子都使用的。 – Damovisa 2010-03-01 14:23:46