有一个奇怪的问题。
在包含MultiSelectList的表单的POST操作期间,我可以看到所有选定的值...到目前为止一切都很好。 但是,如果由于其他字段的某些验证错误而需要重新显示表单,则MultiSelectList下拉字段仅显示第一个选定的值,而不显示在第一个请求期间选择的所有值...
当我在返回视图之前调用ModelState.Clear()时,我能够从数据库重建多选的值列表,并且还显示所有选定的值......但是这种行为不是我想要的100%。
我只想重复使用从post请求中获得的选定ID,但不知何故,这些值会被模型状态覆盖,只显示第一个选定的值。
这里有一些代码:
[HttpPost]
public ActionResult Employer(EmployerViewModel model)
{
...
model.IndustrialSectorsMultiSelectList = new MultiSelectList(industrialSectors, "Id", "Name", model.IndustrialSectorsSelectedIds);
...
return View(model);
}
当我调试我的代码时,我可以看到该model.IndustrialSectorsSelectedIds包含所有选定的值...但是在View中突然只显示第一个值。
有人在这里帮忙吗? : - )
提前致谢!!! 西蒙
更新
很抱歉,如果我不够清楚的话。我不使用ModelState.Clear()。这只是我试图找出最新情况之一,为什么即使我的手动设置值也不会在Post期间拍摄,而它们在Get期间应该工作。它帮助我发现它确实是ModelState以一种只显示第一个选定值的方式覆盖我发布的值。
似乎所选值以逗号分隔的字符串“12,18,33,47”传递。当我在HttpPost Action中重新创建View时,它只需要“12”并忽略列表的其余部分。
这里有更多代码:
视图模型:
public MultiSelectList IndustrialSectorsMultiSelectList { get; set; }
public int[] IndustrialSectorsSelectedIds { get; set; }
采取行动:
EmployerViewModel model = new EmployerViewModel();
Employer employer = ServiceManager.EmployerService.GetEmployerByUser(AppUser);
...
var industrialSectors = ServiceManager.DefaultValuesService.GetIndustrialSectors();
model.IndustrialSectorsMultiSelectList = new MultiSelectList(industrialSectors, "Id", "Name", employer.IndustrialSectors.Select(item => item.Id).ToList());
当我需要重新显示视图时发布操作:
var industrialSectors = ServiceManager.DefaultValuesService.GetIndustrialSectors();
model.IndustrialSectorsMultiSelectList = new MultiSelectList(industrialSectors, "Id", "Name", model.IndustrialSectorsSelectedIds);
查看:
@Html.DropDownListFor(m => m.IndustrialSectorsSelectedIds, Model.IndustrialSectorsMultiSelectList, new { @class = "select_branche form-control", @multiple = "multiple" })
如上所述......在GET期间,所选值在视图中正确显示。 在Post期间,即使在后期操作期间所有选定的值都在我的int []中,也会从模型中获取第一个选定值。所以int []我传递给新的MultiSelectList很好。 仅仅是为了测试我尝试在Post期间构建View与我在Get action中完全相同的代码...在Get中我看到所有值...在帖子中只有第一个。
不知道该怎么做: - (
更新2
当我将以下行添加到我的post action方法时,我设法解决了这个问题。从ModelState中删除int []并在我的ViewModel中设置int [] = null。
var industrialSectors = ServiceManager.DefaultValuesService.GetIndustrialSectors();
model.IndustrialSectorsMultiSelectList = new MultiSelectList(industrialSectors, "Id", "Name", model.IndustrialSectorsSelectedIds);
//Fix issue that modelstate value only sets the first selected value
ModelState.Remove("IndustrialSectorsSelectedIds");
model.IndustrialSectorsSelectedIds = null;
但我仍然不知道为什么会这样。这是某种错误吗?! 任何评论都会很棒。谢谢!
答案 0 :(得分:2)
对不起,也许我太傻了......
在我的视图中将DropDownListFor更改为ListBoxFor时,一切正常。 : - )