LA.NET [EN]

Feb 03

A few days ago I’ve talked about how you could use the helpers to generate dropdowns and listboxes. As I’ve said, you need to build a collection of SelectListItems in order to build these controls. What I didnt’ mentioned at the time was that there is an easy way to convert a custom collection (ie, something which implements IEnumerable<T> interface) into a collection of SelectListItems. To do that, just instantiate the SelectList (or MultiSelectList, if you’re working with listboxes and want to select several values) class.

Here’s a quick example. Suppose you’ve got a class that looks like this:

public class Item    {
    public Int32 Id { get; set; }
    public String Description { get; set; }
}

And that you’ve also got a collection with several items:

var items = new[] {
      new Item {
                  Id = 1,
                  Description = "first"
          },
      new Item {
                  Id = 2,
                  Description = "second"
          },
      new Item {
                  Id = 3,
                  Description = "third"
          }
};

And that you want to fill a dropdown and select item 2. Here’s  how you can do that (I’m using a non-typed view here since I’m in a hurry :),,):

ViewData["optionsDrop"] = new SelectList( items, "Id", "Description", 2 );

As you can see, I’m passing the collection and saying that the Id property should be used for getting the value of the OPTION element and that the Description will return the text for that OPTION element. I’m also saying that element with value should be selected by default. Now, you only need to ensure that your dropdown is named optionsDrop and you’re ready to go:

<%= Html.DropDownList(  "optionsDrop", "Choose an option"   ) %>

And that’s it. More on the MVC platform on future posts.

Leave a Reply

Your email address will not be published. Required fields are marked *


*

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>