我有一个视图,其中有一个从Model属性生成的下拉列表和另外3个从数组属性生成的下拉列表
@Html.DropDownListFor(m => m.AgentType, Model.AgentTypeListItems)
@for (int i = 0; i < Model.AgentTypes.Length; i++)
{
@Html.DropDownListFor(m => m.AgentTypes[i], Model.AgentTypeListItems)
}
控制器方法初始化AgentTypeListItems集合+设置AgentType下拉列表的默认值和集合的3个下拉列表:
var model = new OptionsViewModel();
// for DropDownListFor
model.AgentTypeListItems = new[]
{
new SelectListItem { Text = "1", Value = "1" },
new SelectListItem { Text = "2", Value = "2" },
new SelectListItem { Text = "3", Value = "3" },
};
// 1 dropdown in the model
model.AgentType = "2";
// 3 dropdowns in array
model.AgentTypes = new[] { "3", "2", "1" };
return View(model);
当我在浏览器中打开它时,尽管使用不同的值(!)初始化了AgentTypes数组,但我到处都是“2”:
当我用TextBoxFor替换DropDownListFor时:
@Html.TextBoxFor(m => m.AgentTypes[i])
我在输入中得到了正确的值(!):
这意味着TextBoxFor按预期工作,但DropDownListFor没有。
这是MVC DropDownListFor中的错误吗?
更新 这是模型类:
public class OptionsViewModel
{
public SelectListItem[] AgentTypeListItems { get; set; }
public string AgentType { get; set; }
public string[] AgentTypes { get; set; }
}
答案 0 :(得分:14)
我知道这篇文章已有一年多的历史,但似乎仍然是一个错误。替换
@Html.DropDownListFor(m => m.AgentType, Model.AgentTypeListItems)
@for (int i = 0; i < Model.AgentTypes.Length; i++)
{
@Html.DropDownListFor(m => m.AgentTypes[i], Model.AgentTypeListItems)
}
与
@Html.DropDownListFor(m => m.AgentType, Model.AgentTypeListItems)
@for (int i = 0; i < Model.AgentTypes.Length; i++)
{
@Html.DropDownListFor(m => m.AgentTypes[i], new SelectList(Model.AgentTypeListItems, "Value", "Text", Model.AgentTypes[i])
}
适合我。
答案 1 :(得分:2)
评论你的第一行, @ Html.DropDownListFor(m =&gt; m.AgentType,Model.AgentTypeListItems) 那会发生什么?
试试这个:
@for (int i = 0; i < Model.AgentTypes.Length; i++) { string selected = Model.AgentTypes[i]; @Html.DropDownListFor(m => selected, new SelectList(Model.AgentTypeListItems, "Text", "Value",Model.AgentTypes[i])) }
答案 2 :(得分:0)
我想知道这是否与WPF和Windows Forms中的情况类似,其中使用相同的源项目列表选项将所有UI元素“链接”在幕后?我记得在这些情况下必须创建列表对象的单独副本。可能值得一试。