-->

MVC4结合下拉列表中的列表(错误)(MVC4 binding drop down list in

2019-08-17 01:25发布

我有一个观点下面的代码。 (index.cshtml)

绑定问题

  • 第一个下拉选择正确的价值的基础上,“ChildItem”编辑模板。
  • 使用内联下拉列表中的第二个例子不工作 ,我不希望创建一个编辑模板,只是为了显示下拉值。
  • 奇怪的是,TextBoxFor会显示正确的值。 这似乎是一个问题,只是在下拉列表中。

如何解决的结合,使得第二下拉作品? 我调试了。 这样看来,ViewData.Eval没有拿起从正确的价值_.Children[i].ChooseId

更新(错误)
这是一个确认的错误(低优先级,怎么样?)在MVC框架http://aspnet.codeplex.com/workitem/8311

@using (Html.BeginForm())
{
    for (int i = 0; i < Model.Children.Count(); i++)
    {
       <p>A: @Html.EditorFor(_ => _.Children[i], "ChildItem")</p>
       <p>B: @Html.DropDownListFor(_ => _.Children[i].ChooseId, TestModel.PeopleSelect)</p>
    }
    <button type="submit">GO</button>
}

我已经尝试使用DropDownListFor(_ => Model.Children[i].ChooseId)相同的结果。
使用TextBoxFor(_ => _.Children[i].ChooseId)示出正确值, 奇怪?

仅供参考这里是ChildItem.cshtml

@using dropdown.Controllers
@using dropdown.Models
@model dropdown.Models.TestPerson
@Html.DropDownListFor(_ => _.ChooseId, TestModel.PeopleSelect)

它看起来像这样:

Answer 1:

我后来发现这一点: http://aspnet.codeplex.com/workitem/8311这是一个确认的错误。

我已经找到了唯一的解决方法是这样的。

马克所选项目

@Html.DropDownListFor(_ => _.Children[i].ChooseId, Mark(TestModel.PeopleSelect, Model.Children[i].ChooseId))

马克功能/扩展方法

@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;
    }
}


Answer 2:

你可以把物品放入一个局部视图,并为您的孩子对象加载,还是......

你可以选择做foreach对孩子收集循环,并使用它像这样:

foreach (var itm in Model.Children)
{
    @Html.DropDownListFor(modelItem => itm.ChooseId,
          new SelectList( (IEnumerable<SelectListItem>)TestModel.PeopleSelect, "Value", "Text", itm.ChooseId),
          htmlAttributes: new { @class = "form-control" }
    )
}

这假定TestModel.PeopleSelect已作为创建SelectListItem[]IEnumerable<SelectListItem> 代码做,妥善是我在一个相关的问题的答案: ASP.NET MVC4型号的子集合下拉列表不正确的结合

做一个for对孩子收集循环给我的错误:

可以不适用[]索引,以类型的表达式“ICollection的<儿童>”

所以,我不会建议。



文章来源: MVC4 binding drop down list in a list (bug)