asp.net-mvc 如何使用 asp.net mvc 3 和 ListBoxFor 显示多个选择?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8696358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:39:46  来源:igfitidea点击:

How to show multiple selected with asp.net mvc 3 and ListBoxFor?

asp.net-mvcasp.net-mvc-3

提问by chobo2

I have this VM properties

我有这个虚拟机属性

  public IList<Guid> SelectedEligiableCategories { get; set; }
  public IList<SelectListItem> EligiableCategories { get; set; }  

I have this helpers in my view

我有这个帮手

  @Html.LabelFor(x => x.EligibleCategoryFrmVm.SelectedEligiableCategories, "Eligible Categories:")
    @Html.ListBoxFor(x => Model.EligibleCategoryFrmVm.SelectedEligiableCategories, Model.EligibleCategoryFrmVm.EligiableCategories, new { @class = "eligibleCategoryListBox" }) 

I have this code in my controller

我的控制器中有此代码

  List<SelectListItem> eligibleCategoriesListItems = Mapper.Map<List<EligibleCategory>, List<SelectListItem>>(eligibleCategories);
  foreach (var rewardTier in creditCard.RewardTiers)
        {
            CbRewardTierFrmVm rewardTierFrmVm = new CbRewardTierFrmVm();
            rewardTierFrmVm.EligibleCategoryFrmVm.EligiableCategories = eligibleCategoriesListItems;

            foreach (var ec in rewardTier.EligibleCategories)
            {
                rewardTierFrmVm.EligibleCategoryFrmVm.SelectedEligiableCategories.Add(ec.Id);
            }

            vm.CbRewardTierFrmVm.Add(rewardTierFrmVm);
        }

Yet when I load up my view. None of values for my ListBox are selected. I am not sure why. If this was a selectList this would work as it would match up the SelectedEligiableCategories to the value in the list.

然而,当我加载我的视图时。我的 ListBox 没有任何值被选中。我不知道为什么。如果这是一个 selectList,这将起作用,因为它将 SelectedEligiableCategories 与列表中的值相匹配。

I am not sure if this is because there is multiple selects

我不确定这是不是因为有多个选择

Edit

编辑

<select name="CbRewardTierFrmVm[63b504c0-0f9a-47ba-a8ff-db85f48d5f0f].EligibleCategoryFrmVm.SelectedEligiableCategories" multiple="multiple" id="CbRewardTierFrmVm_63b504c0-0f9a-47ba-a8ff-db85f48d5f0f__EligibleCategoryFrmVm_SelectedEligiableCategories" data-val-required="Must choose at least one eligible category." data-val="true" class="eligibleCategoryListBox ui-wizard-content ui-helper-reset ui-state-default" style="display: none;">
   <option value="ed2bb5f9-4565-4f69-ab15-9fca011c0692">Gas</option>
</select>

Do you think it is because I am using http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/?

您认为这是因为我使用的是http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/吗?

Edit2

编辑2

I gone ahead and make an example. I must be missing something(not sure what). When I use "Darin Dimitrov" it works.

我继续举了一个例子。我一定错过了什么(不确定是什么)。当我使用“Darin Dimitrov”时,它可以工作。

I switched the example to a dropdown as I am getting the same problem with it as well.

我将示例切换到下拉列表,因为我也遇到了同样的问题。

In this example I am not using a viewmodel since my initial assumption was somehow the helper I was using from Steven Sanders might be effecting it so I was going off his example.

在这个例子中,我没有使用视图模型,因为我最初的假设是以某种方式我从史蒂文桑德斯使用的助手可能会影响它,所以我离开了他的例子。

This does not seem to be the case as I removed it and still get this problem.

情况似乎并非如此,因为我将其删除并仍然遇到此问题。

  public class Gift
    {
        public string Name { get; set; }
        public double Price { get; set; }
        public string SelectedItem { get; set; }
        public IList<SelectListItem> Items { get; set; }
    }


 public ActionResult Index()
    {
        List<SelectListItem> items = new List<SelectListItem>
        {

              new SelectListItem {Value = "",Text ="--"},
              new SelectListItem {Value = "1",Text ="1"},
              new SelectListItem {Value = "2",Text ="2"},
        };


        var initialData = new[] {
            new Gift { Name = "Tall Hat", Price = 39.95, Items = items, SelectedItem = "2" },
            new Gift { Name = "Long Cloak", Price = 120.00, Items = items, SelectedItem = "1"  }
         };

        return View("Index3",initialData);
    }

@model IList<EditorDemo.Models.Gift>

@{
    ViewBag.Title = "Index3";
}

@for (int i = 0; i < Model.Count; i++)
{
     @Html.DropDownListFor(x => x[i].SelectedItem, new SelectList(Model[i].Items, "Value", "Text")) 
}

It seems to not be able to handle when you put it in forloop and try it make more than one dropdown list.

当您将其放入 forloop 并尝试创建多个下拉列表时,它似乎无法处理。

回答by Darin Dimitrov

The following works for me.

以下对我有用。

Model:

模型:

public class MyViewModel
{
    public IList<Guid> SelectedEligiableCategories { get; set; }
    public IList<SelectListItem> EligiableCategories { get; set; } 
}

Controller:

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            SelectedEligiableCategories = new[]
            {
                // preselect the second and the fourth item
                new Guid("35830042-3556-11E1-BCDC-A6184924019B"),
                new Guid("4253876A-3556-11E1-BC17-B7184924019B")
            }.ToList(),

            EligiableCategories = new[]
            {
                new SelectListItem { Value = "2DA62E3A-3556-11E1-8A0A-9B184924019B", Text = "item 1" },
                new SelectListItem { Value = "35830042-3556-11E1-BCDC-A6184924019B", Text = "item 2" },
                new SelectListItem { Value = "3D07EBAC-3556-11E1-8943-B6184924019B", Text = "item 3" },
                new SelectListItem { Value = "4253876A-3556-11E1-BC17-B7184924019B", Text = "item 4" },
            }
        };
        return View(model);
    }
}

View:

看法:

@model MyViewModel

@using (Html.BeginForm())
{
    @Html.ListBoxFor(
        x => x.SelectedEligiableCategories, 
        Model.EligiableCategories,  
        new { @class = "eligibleCategoryListBox" }
    )
}

Result:

结果:

enter image description here

在此处输入图片说明



UPDATE:

更新:

Now that you have shown an example allowing to illustrate the problem, you could specify the selected item when building the SelectList:

现在您已经展示了一个示例来说明问题,您可以在构建时指定所选项目SelectList

@Html.DropDownListFor(
    x => x[i].SelectedItem, 
    new SelectList(Model[i].Items, "Value", "Text", Model[i].SelectedItem)
)

The reason a value was not preselected was because you were binding the dropdownlist to a list of properties (x => x[i].SelectedItem) whereas in my example I was using a simple property.

未预选值的原因是您将下拉列表绑定到属性列表 ( x => x[i].SelectedItem),而在我的示例中,我使用的是简单属性。

And if you wanted to do this with the ListBoxFor helper you could use the following:

如果你想用 ListBoxFor 助手来做到这一点,你可以使用以下内容:

@Html.ListBoxFor(
    x => x[i].SelectedItems, 
    new MultiSelectList(Model[i].Items, "Value", "Text", Model[i].SelectedItems)
)

The SelectedItemsproperty becomes a collection and we use a MultiSelectListinstead of a SelectList.

SelectedItems属性成为一个集合,我们使用 aMultiSelectList而不是 a SelectList

回答by Jalal El-Shaer

The main problem is using

主要问题是使用

@Html.DropDownListFor

instead of this

而不是这个

@Html.ListBoxFor

Using the DropDownListFor will NOT help you with multiple values, whatever you do and no matter what your model is. Once you use ListBoxFor ... it will automatically just work !

无论您做什么,无论您的模型是什么,使用 DropDownListFor 都不会帮助您处理多个值。一旦你使用 ListBoxFor ......它会自动工作!