«

»

Feb
26

Multi-Select List Box in ASP.NET MVC

Recently I have been working on an MVC site using the Entity Framework. 

I have some related entities in my EF model, as show below in the form of “Reader” and “Category”, and the relationship between them, i.e. many to many.

When it came to proucing a view and action to perofrm the Create Reader action, I was somewhat puzzled as to how I could allow the user to select one or more categories for a reader. 

I started by having a view model that contained a list of all possible categories and then looping around these in my view and writing a check box out for each one.  When the form was submitted I looked through the form collection to find if any of the category check boxes had been selected.  I didn’t like this one bit and so I set out to find a cleaner way of carrying it out.

After some (quite a lot actually) searching, I stumbled accross the MultiSelectList type, which I could use in my ViewModel and then allow the default model binding to step in and do the leg work for me :) Great!

So, I created a view model, a simplified version of which you can see below;

    public class ReaderCreateViewModel : CustomViewModelBase
    {

        public ReaderCreateViewModel()
        {
            ReaderDetails = new Reader();
            CategoriesList = GetCategories(null);
        }

        public Reader ReaderDetails { get; set; }
        public MultiSelectList CategoriesList { get; private set; }
        public int[] SelectedCategories { get; set; }

        public MultiSelectList GetCategories(int[] selectedValues)
        {
            var te = new myEntities();
            List<Category> categories = te.Categories.ToList();
            return new MultiSelectList(categories, “id”, “Name”, selectedValues);
        }
    }

 As you can see from the code above, the view model contains my Reader entity, a list of type MultiSelectList, which is a list of available categories and an array of integers which represent the Id of any selected Categories.

Then to add a listbox to my view that will bind the MultiSelectList, I simply insert the following into my view.

            <p>
             <label for=”SelectedCategories”>Categories:</label>
        <%= Html.ListBox(“SelectedCategories”, Model.CategoriesList) %>
            </p>

Finally in my controller, I can simply check the SelectedItems object in my model for any selected Ids and add them to the Reader Categories list like this;

            if (model.SelectedCategories != null)
            {
                foreach (var selectedCat in model.SelectedCategories)
                {
                    int selectedCatId = selectedCat;
                    Category category = DataContext.Categories.Where(c => c.id                  == selectedCatId).FirstOrDefault();
                    reader.Categories.Add(category);
                }
            }

And that’s it.  Now there is probably a much better way of doing all or some of the above, but this worked perfectly for me when I needed it, so I hope it helps someone else out as well.  The final multi-select list box looked something like this;


Kick It on DotNetKicks.com
No TweetBacks yet. (Be the first to Tweet this post)

Technorati Tags: , ,

7 comments

No ping yet

  1. trendbender says:

    Helpul post, thx.

  2. rajani says:

    if we want to show multiple columns from table into a listbox then how we do it please help me

  3. Brandy Merkling says:

    Have been looking at doing some site optimization and improving the design on my site for a long time, so this post has been really useful. Clear read also, so thank you!

  4. Arie says:

    Nice. Very clean. Thanks a lot.

  5. Stuart says:

    Life saver

  6. Slonjo Ruels says:

    Kudos!

  7. jhil says:

    what is “myEntities” in the below code line ?

    var te = new myEntities();

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>