我意识到关于这个特定问题有很多关于SO的问题,但是我已经发现的答案都没有做到我正在做的事情。
查看模型
public FreightDiscountViewModel()
{
Sign = new List<SelectListItem>();
States = new List<SelectListItem>();
FreightDiscounts = new List<FreightDiscountModel>();
PopSign();
PopStates();
}
public List<FreightDiscountModel> FreightDiscounts { get; set; }
public List<SelectListItem> States { get; set; }
public List<SelectListItem> Sign { get; set; }
private void PopSign ()
{
Sign.Add(new SelectListItem { Text = "-", Value = "-" });
Sign.Add(new SelectListItem { Text = "+", Value = "+" });
}
private void PopStates ()
{
States.Add(new SelectListItem { Value = "AL", Text = "Alabama" });
States.Add(new SelectListItem { Value = "AK", Text = "Alaska" });
States.Add(new SelectListItem { Value = "AZ", Text = "Arizona" });
States.Add(new SelectListItem { Value = "AR", Text = "Arkansas" });
States.Add(new SelectListItem { Value = "CA", Text = "California" });
States.Add(new SelectListItem { Value = "CO", Text = "Colorado" });
}
}
查看
@for (var i = 0; i < Model.FreightDiscounts.Count; i++ )
{
<tr>
<td>@Html.DropDownListFor(x => x.FreightDiscounts[i].State, Model.States, new { @class = "form-control" })</td>
</tr>
}
我正在我的视图模型中填充我的FreightDiscounts
列表而没有问题,现在正在进行测试,我只返回了1个州,阿拉斯加州。因此,在该列表中填充的1条记录具有以下信息
AK,
US,
50,
0,
+
我的问题是,当视图加载时,1记录的状态下拉列表设置为Alabama(AL),而不是像我期望的那样设置为Alaska。有没有人看到我遗失的任何明显事物?\
修改
JamieD77的答案解决了我的问题。我将View更改为以下内容。
<td>
@Html.DropDownListFor(x => x.FreightDiscounts[i].State,
new SelectList(Model.DStates, "key", "value", Model.FreightDiscounts[i].State), new { @class = "form-control" })
</td>
我将View Model更改为以下
public Dictionary<String, String> DStates { get; set; }
DStates.Add("AL","Alabama" );
DStates.Add("AK","Alaska" );
答案 0 :(得分:4)
尝试使用SelectList并在构建下拉列表
时设置所选项目@Html.DropDownListFor(x => x.FreightDiscounts[i].State,
new SelectList(Model.States, "Value", "Text", x.FreightDiscounts[i].State),
new { @class = "form-control" })
答案 1 :(得分:0)
可能是因为您的文本和值字段被颠倒了?
编辑:OP更新了他的代码,他们最初被颠倒了。