MVC DropDownListFor 在模型包含列表的情况下不设置值

问题描述

我有一个模型如下

class MyModel 
{
     public List<SomeSetting> Settings {get; set;} = List<SomeSetting> ();
}

class SomeSetting   // This will contain two properties only at the moment
{
     public List<MyProperty> Properties { get; set; } = new List<MyProperty>();
}

public MyProperty 
{
     public string Name { get; set; }
     public string Value { get; set; }
}

此模型填充在控制器中

model = new MyModel();

var SomeSetting1 = new SomeSetting();
SomeSetting1.Properties.Add(new MyProperty () { Name = "X",Value = "XX" })
SomeSetting1.Properties.Add(new MyProperty () { Name = "Y",Value = "YY" })
model.Settings.Add(SomeSetting1);

var SomeSetting2 = new SomeSetting();
SomeSetting2.Properties.Add(new MyProperty () { Name = "X1",Value = "XX1" })
SomeSetting2.Properties.Add(new MyProperty () { Name = "Y1",Value = "YY1" })
model.Settings.Add(SomeSetting2);

return View(model);

一个包含所有属性名称的常量文件

class MyConstants {
     public const string[] ALL_VALID_PROP_NAMES = new string[] { "X","Y","Z","X1","Y1","Z1" }
}

现在我在视图中为这个模型创建了一个下拉列表

@for (var inx = 0; inx < Model.Settings.Count; inx++)
{
    @Html.DropDownListFor(model => model.Settings[inx].Properties[0].Name,new 
    SelectList(MyConstants.ALL_VALID_PROP_NAMES),htmlAttributes: new { @class = "form-control"})

    @Html.DropDownListFor(model => model.Settings[inx].Properties[1].Name,htmlAttributes: new { @class = "form-control"})

}

用户在 UI 上设置值时,值会在我的模型中的相应列表对象中设置。 但是当将包含值的模型提供给 UI 时,下拉列表中并未选择实际值。

有什么线索吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)