ASP.NET MVC MultiSelectList使用选定的值不正确选择 [英] ASP.NET MVC MultiSelectList with selected values not selecting properly

查看:111
本文介绍了ASP.NET MVC MultiSelectList使用选定的值不正确选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道别人都问这个问题,但我完全糊涂了这个:

I know others have asked this question, but I'm totally confused by this:

这显示没有值下拉列表中选择:

This displays the dropdown with no values selected:

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

这显示与我传递(Model.items)的值适当选择像我期望的那样下拉:

This displays the dropdown with the values that I'm passing in (Model.items) selected properly like what I'd expect:

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

但问题是,这个项目现名为somethingelse当我张贴。我知道我可以破解解决这个可是这是怎么回事?

But the problem is that this item is now named "somethingelse" when i POST. I know I can hack around this but what's going?

推荐答案

你有这个问题可以用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" })%>

好运气

这篇关于ASP.NET MVC MultiSelectList使用选定的值不正确选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆