【发布时间】:2016-03-23 02:47:13
【问题描述】:
这是模型:
public class PolicyDetail
{
public Policy Policy { get; set; }
public IEnumerable<Insured> Insured { get; set; }
public IEnumerable<Risk> Risk { get; set; }
public IEnumerable<Construction> Construction { get; set; }
}
构造看起来像这样:
public class Construction
{
public int ConstructionID { get; set; }
public string ConstructionType { get; set; }
}
而在数据库中,只有 4 行。它基本上是一个枚举。
Risk 内部有这个属性:
public int ConstructionID { get; set; }
在将模型发送到视图之前,我们填充 PolicyDetail 中的每个对象,其中 Insured 和 Risk 是 Policy 的子级。每次构造都加载了所有四行。
因此,在模型中,我们列出了所有风险。当我们显示它们时,我们希望将 Constructions 显示为下拉列表,并将所选值设置为 Risk.ConstructionID 中的任何值。
令人惊讶的是,这些简单的下拉菜单在 MVC 中能引起多大的关注。
@foreach (var item in Model.Risk)
{
... Other items in Risk
<div class="form-group">
@Html.Label("Construction Type", new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList(?????????)
</div>
</div>
... Other items in Risk
}
如何用来自
的所有项目填充该下拉列表Model.Constrution
并将所选项目设置为其中的内容
item.ConstrucitonID
?
谢谢!
编辑:
这是有效的解决方案:
@Html.DropDownList("ConstructionType", new SelectList(Model.Construction.Distinct().ToList(), "ConstructionID", "ConstructionType", item.ConstructionID))
【问题讨论】:
标签: c# asp.net-mvc dropdownlistfor