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