Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

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/ ?

Edit2

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

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.

like image 209
chobo2 Avatar asked Jan 01 '12 23:01

chobo2


2 Answers

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:

@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.

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

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

The SelectedItems property becomes a collection and we use a MultiSelectList instead of a SelectList.

like image 171
Darin Dimitrov Avatar answered Oct 11 '22 09:10

Darin Dimitrov


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 !

like image 36
Jalal El-Shaer Avatar answered Oct 11 '22 09:10

Jalal El-Shaer