Practical .NET

Add a Multi-Select ListBox or DropDownList to Your ASP.NET MVC View

Peter doesn't like them, but that doesn't mean you have to hate 'em, too -- here's how to add a listbox or dropdown list to your View that lets users select multiple items.

Personally, I think adding a listbox to your page that allows a user to select multiple items is a mistake. My guess is that most users don't know how to use a multiselect list and, without some special directions on the page, won't even know that they can make multiple selections.

Really, my feeling is that, if you need multiple selections, you should be using checkboxes (which users do know how to use and instantly recognize). I've discussed a complete solution -- which tells you both what the user selected and left unselected -- looks like elsewhere.

Still, if you're tight for screen space, you might find yourself forced into using a multiselect list.

Your first step is to create, typically in an Action method, a MultiSelectList object to hold all of the choices you'll present to the user. When you create the list, you'll want to pass three parameters: the collection of objects (in the following code that's sales orders for a customer), the property whose value you want sent back to the server for the selected items (Id), and the property whose value you want to display in the list (OrderDate):

ViewBag.Orders = New MultiSelectList(cust.SalesOrders, "Id", "OrderDate")

You can pass the list through a property on your View's Model object, but I typically pass my lists using the ViewBag, as I've done here.

In your View, you can display your list using a DropDownList (adding the multiple attribute) or a ListBox. Either way, you'll get the same HTML. The two versions of the code look like this:

@Html.DropDownListFor(Function(m) m.SalesOrders, DirectCast(ViewBag.Orders, MultiSelectList), 
  New With {.multiple = "multiple"})
@Html.ListBoxFor(Function(m) m.SalesOrders, DirectCast(ViewBag.Orders, MultiSelectList))

When users submit the form (after making their choices), what's going to arrive at the Action method is an array of whatever property you specified in the MultiSelectList's second parameter. I specified the SalesOrder object's Id property, which is an Integer, so I'll be getting an array of Integers. The property I passed to the DropDownListFor was called SalesOrders, so that's the name I should expect to get the data back in.

Of course, it's possible that the user won't have selected anything, in which case the array will be null/Nothing, and you should check for that. If the array is present, you can process it with a For…Each loop. Putting that all together, the Action method that processes my submitted form data will look something like this:

<HttpPost>
Function Index(cust As Customer, SalesOrders As Integer()) As ActionResult
  '...code to process Customer object...
  If SalesOrders IsNot Nothing Then      
    For Each Ord As Integer In SalesOrders
      '...code to process selected items
    Next
  End If
End Function

I still don't like 'em, though.

About the Author

Peter Vogel is a system architect and principal in PH&V Information Services. PH&V provides full-stack consulting from UX design through object modeling to database design. Peter tweets about his VSM columns with the hashtag #vogelarticles. His blog posts on user experience design can be found at http://blog.learningtree.com/tag/ui/.

comments powered by Disqus

Featured

  • Hands On: New VS Code Insiders Build Creates Web Page from Image in Seconds

    New Vision support with GitHub Copilot in the latest Visual Studio Code Insiders build takes a user-supplied mockup image and creates a web page from it in seconds, handling all the HTML and CSS.

  • Naive Bayes Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the naive Bayes regression technique, where the goal is to predict a single numeric value. Compared to other machine learning regression techniques, naive Bayes regression is usually less accurate, but is simple, easy to implement and customize, works on both large and small datasets, is highly interpretable, and doesn't require tuning any hyperparameters.

  • VS Code Copilot Previews New GPT-4o AI Code Completion Model

    The 4o upgrade includes additional training on more than 275,000 high-quality public repositories in over 30 popular programming languages, said Microsoft-owned GitHub, which created the original "AI pair programmer" years ago.

  • Microsoft's Rust Embrace Continues with Azure SDK Beta

    "Rust's strong type system and ownership model help prevent common programming errors such as null pointer dereferencing and buffer overflows, leading to more secure and stable code."

  • Xcode IDE from Microsoft Archrival Apple Gets Copilot AI

    Just after expanding the reach of its Copilot AI coding assistant to the open-source Eclipse IDE, Microsoft showcased how it's going even further, providing details about a preview version for the Xcode IDE from archrival Apple.

Subscribe on YouTube

Upcoming Training Events