且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET MVC MultiSelectList使用选定的值不正确选择

更新时间:2023-11-08 08:49:40

你有这个问题可以用Model.Items作为参数。在code

The problem you have is using Model.Items as a parameter. The code

<%= Html.DropDownList("items", new MultiSelectList(Model.AvailableItems,
    "id", "name", Model.items), new { multiple = "multiple" })%>

不实际工作,你期望的那样。它的工作,因为下拉列表的名称是项目。这是因为有所谓的项目贴回你的动作的表格参数。这参数被存储在动作的ViewState(不ViewData的混淆)。
该Html.DropdownList()认为,有一个名为一样的,你命名你的下拉列表,并使用该参数的ViewState制定出选定值的ViewState的参数。 它完全忽略你传递的Model.items。

如果任何人都可以解释不能够覆盖默认行为的逻辑,那么我很乐意听到这种说法。

If anyone can explain the logic of not being able to override the default behavior then I'd love to hear it.

所以,这是你的第一个问题。为了解决这一切,你需要做的就是重新命名下拉到别的东西 - 就像你在你的第二个例子一样。现在你的第二个问题发挥作用:选定项的列表必须是简单对象的集合(我认为它实际上需要有一个IEnumerable,但我不是100%确定)

So, that's your first problem. To get around it all you have to do is to rename the dropdown to something else - exactly like you did in your second example. Now your second problem comes into play: the list of selected items must be a collection of simple objects (I think it actually needs to be an IEnumerable but I'm not 100% sure).

DropDownList控件()方法会尽量选择那些值匹配到你的 AvailableItems 收藏价值。如果不能做到这一点,它会尝试来匹配文本。

The DropDownList() method will try and match those selected values to the Value in your AvailableItems collection. If it can't do that it will try to match against the Text.

所以,尽量这看看它是否工作

So, try this to see if it works

<%= Html.DropDownList("somethingelse", new MultiSelectList(Model.AvailableItems,
    "id", "name", Model.items.Select(c=> c.name)), new { multiple = "multiple" })%>

好运气