我遇到了一个问题,无法在下拉列表中选择正确的值。它总是默认为索引零。但是,在另一个地方,我有一个视图,渲染得很好,并选择了正确的值。我不明白其中的区别。
这是一个精简版本的视图,可以正常工作:
@model AppName.Models.Guest
@using (Html.BeginForm())
{
Attending Ceremony?<br />
@Html.DropDownListFor(x => x.ConfirmCeremony, new SelectList(new Dictionary<string, string>
{
{"No Answer", "No Answer"},
{"Yes", "Yes"},
{"No", "No"},
{"Maybe", "Maybe"}
}, "key", "value"))
@Html.ValidationMessageFor(x => x.ConfirmCeremony)
<br />
Attending Reception?<br />
@Html.DropDownListFor(x => x.ConfirmReception, new SelectList(new Dictionary<string, string>
{
{"No Answer", "No Answer"},
{"Yes", "Yes"},
{"No", "No"},
{"Maybe", "Maybe"}
}, "key", "value"))
@Html.ValidationMessageFor(x => x.ConfirmReception)
}
这个视图的模型是自定义类型 Guest
,当它渲染“出席仪式”和“出席酒会”下拉列表时,它会正确选择存储在模型中的选项。因此,如果我回来编辑这个客人,我可以看到上次编辑时选择的内容,正如预期的那样。这个视图是仅供管理员使用的视图,并且比下一个视图拥有更多的选项。
这是一个精简版的视图,无法工作:
@model AppName.Models.Invite @*Invite has navigation property .Guests which is a collection of custom type Guest*@
@using (Html.BeginForm("SaveRSVP", "Wedding"))
{
@Html.HiddenFor(x => x.Id)
<table cellpadding="15px" cellspacing="0">
<tr>
<th>
Name
</th>
@if (Model.Guests.Any(x => x.InvitedToCeremony))
{
<th>
Attending Ceremony?
</th>
}
<th>
Attending Reception?
</th>
</tr>
@Html.EditorFor(x => x.Guests)
</table>
<br />
<input type="submit" value="Save Responses" />
}
Html.EditorFor(x => x.Guests)
加载包含出席仪式和出席招待会下拉列表的编辑模板。以下是编辑模板:
@model AlexAndNikki.Models.Guest
<tr>
<td>
@Html.HiddenFor(x => x.GuestID)
@Model.FullName()
</td>
@if (Model.Invite.Guests.Any(x => x.InvitedToCeremony))
{
<td>
@if (Model.InvitedToCeremony)
{
<text>
@Html.DropDownListFor(x => x.ConfirmCeremony, new SelectList(new Dictionary<string, string>
{
{"No Answer", "No Answer"},
{"Yes", "Yes"},
{"No", "No"},
{"Maybe", "Maybe"}
}, "key", "value"))
@Html.ValidationMessageFor(x => x.ConfirmCeremony)
</text>
}
else
{
<text>
No more invites.
</text>
}
</td>
}
<td>
@Html.DropDownListFor(x => x.ConfirmReception, new SelectList(new Dictionary<string, string>
{
{"No Answer", "No Answer"},
{"Yes", "Yes"},
{"No", "No"},
{"Maybe", "Maybe"}
}, "key", "value"))
@Html.ValidationMessageFor(x => x.ConfirmReception)
</td>
</tr>
这确实呈现了下拉列表,如果我选择项目并进行POST,则值将正确发送到服务器。但是,下拉列表没有选择正确的值。我甚至在下拉列表上方以纯文本形式显示了编辑器模型中存储的值,以验证正确的值是否传递给了编辑器,并且确实如此。这是下拉列表的问题。我怀疑这与每个附加到邀请的
Guest
重复使用此编辑器有关,但我无法确定问题所在。注意:如果我不使用编辑器,而是在视图中执行以下操作,则会发生相同的情况:
@for (int i = 0; i < Model.Guests.Count; i++)
{
@Html.DropDownListFor(x => x.Guests.ToList()[i].ConfirmCeremony, new SelectList(new Dictionary<string, string>
{
{"No Answer", "No Answer"},
{"Yes", "Yes"},
{"No", "No"},
{"Maybe", "Maybe"}
}, "key", "value"))
}
同样的问题也存在于这里,下拉列表不会选择框中的值。它只停留在索引0。