Skip to main content
 首页 » 编程设计

c#之ASP.NET MVC4 模型的子集合下拉列表未正确绑定(bind)

2024年02月06日29emanlee

我遇到了与此相同的问题 here我相信,但解决方法对我不起作用。 我的问题是我在主视图的 ViewModel 中有一个子模型集合。它们包含要在两个字段中显示的数据,一个下拉列表和一个密码字段。每个下拉列表选择必须是唯一的。一切都在保存并正确发送到 View ,但是当调用 View 时下拉列表未绑定(bind)到所选值,但密码字段是。它们都默认为第一个选择,即使它们应该绑定(bind)到的属性是唯一的并且只有一个可以是第一个值。任何帮助或见解表示赞赏。谢谢。

这是我认为出现问题的部分。我已经评论了我的努力并尝试了上述链接的解决方法但无济于事:

@functions { 
private IEnumerable<SelectListItem> Mark(IEnumerable<SelectListItem> items, object Id) 
{ 
    foreach (var item in items) 
        if (string.CompareOrdinal(item.Value, Convert.ToString(Id)) == 0) 
            item.Selected = true; 
    return items; 
} 
} 
 
 
 
@for (int j = 0; j < Model.PasswordResetQuestionUserAnswers.Count(); j++) 
{ 
@Html.Hidden("PasswordResetQuestionUserAnswers.Index", j) 
@Html.HiddenFor(p => Model.PasswordResetQuestionUserAnswers[j].Id) 
@Html.HiddenFor(p => Model.PasswordResetQuestionUserAnswers[j].UserId) 
<div class="form-group"> 
<label class="col-md-2 control-label">Password Reset Question @(j+1)</label> 
<div class="col-md-6"> 
@*@Html.DropDownList("PasswordResetQuestionUserAnswers[" + j + "].PasswordResetQuestionId", Model.PasswordResetQuestionList, new { @class = "form-control passwordQuestion" })*@ 
@*@Html.DropDownListFor(x => Model.PasswordResetQuestionUserAnswers[j].PasswordResetQuestionId, Model.PasswordResetQuestionList, new { @class = "form-control passwordQuestion" })*@ 
@Html.DropDownListFor(x => Model.PasswordResetQuestionUserAnswers[j].PasswordResetQuestionId, Mark(Model.PasswordResetQuestionList, Model.PasswordResetQuestionUserAnswers[j].PasswordResetQuestionId)) 
</div> 
</div> 
<div class="form-group"> 
<label class="col-md-2 control-label">Password Reset Answer @(j+1)</label> 
<div class="col-md-6"> 
@Html.Password("PasswordResetQuestionUserAnswers[" + j + "].Answer", Model.PasswordResetQuestionUserAnswers[j].Answer, new { @class = "form-control passwordQuestionUserAnswer" }) 
@*@Html.PasswordFor(x => Model.PasswordResetQuestionUserAnswers[j].Answer, new { @class = "form-control passwordQuestionUserAnswer" })*@ 
</div> 
</div> 
} 

请您参考如下方法:

我刚刚遇到了同样的问题。这种语法对我有用:

 @Html.DropDownListFor(x => x.ChildCollection[i].ChildID, new SelectList(ViewBag.ChildCollectionSelect as SelectList, "Value", "Text", Model.ChildCollection[i].ChildID)) 

将 SelectList 定义为新的,然后专门设置从模型中选择的值。