LA.NET [EN]

Mar 12

The MVC framework: the DropDownList control

Posted in ASP.NET MVC      Comments Off on The MVC framework: the DropDownList control

Today we’re going to keep looking at the futures assembly and we’ll take a peek at the DropDownList control. Currently, the class exposes the following properties:

  • Name: used to identify the control and recover the collection of SelectListitems that might have been added to the view data dictionary;
  • OptionLabel: used for passing the text that is set up as the top option show to the user by default.

As you might expect, the rendering is really similar to what happens in the TextBox: the difference is that in this case you’ll end up having several OPTION elements rendered. If you look at the code, you’ll notice that this is still work in progress (and that’s why it’s still on the futures assembly!): you can only generate DropDownLists but it seems like in the future we’ll have an intermediary class for holding common code and then two specialized classes for rendering DropDownList and ListBoxes. That’s the only reason I can  think of for having code that can generates dropdowns or listboxes and that is always hard coded for generating dropdowns…

Ok, so let’s see how we can use this control to add a drop down to a view. We’ll start with the markup:

<mvc:DropDownList runat="server"
      name="myDrop"
      optionlabel="choose an option" />

Now, we need to ensure that there’s an entry in the view data dictionary with the name myDrop which has a collection of items. Since this is demo code, I’ll just add these lines to the action method that returns the view that contains the markup presented in the previous snippet:

var items = new[]{
                               new SelectListItem
                                   {
                                           Text = "Option 1",
                                           Value = "Opt1"
                                   },
                               new SelectListItem
                                   {
                                           Text = "Option 2",
                                           Value = "Opt2"
                                   }
                       } ;
ViewData["myDrop"] = items;

And that’s all you need to fill the dropdown. btw, don’t forget that you can use the SelectList class for passing a custom collection of items like it was shown here. And that’s all for  today. Keep tuned for more about MVC.