Setting SELECTED in ASP.NET MVC DropDowns

Microsoft’s ASP.NET MVC framework has a nice little helper for creating drop-down lists (it outputs a SELECT tag with OPTION sub-tags in HTML). It’s called Html.DropDownList, and it’s a shortcut to HtmlHelper.DropDownList. It takes three parameters: a field ID, a list of the items to display, and a default item representing “none of these values.”

But how do you tell it to pre-select a value, i.e. set the value that shows when the page loads? In HTML, you do this by appending SELECTED to the end of the OPTION tag that’s selected.

The solution is a bit complicated; the second parameter of your function call (the list of items) should be of type SelectList. SelectList has a parameter called SelectedValue, which is, unfortunately, read-only.

But there’s hope! There are two constructors for a SelectList (actually, four, but we’re just interested in two): the usual one (that just takes the list of items), and a second one that allows you to pass in the selected object.

Just pass in the right object from your collection, and you’re all set! You could do either of the following:

// Solution #1
Post[] posts = ... // from somewhere
s = new SelectList(posts, posts[3]); // select the fourth item

// Solution #2
Post[] posts = ...
post selected = posts[3]; // or set somewhere else
s = new SelectList(posts, selected)

About Ashiq Alibhai, PMP

Ashiq has been coding C# since 2005. A desktop, web, and RIA application developer, he's touched ASP.NET MVC, ActiveRecord, Silverlight, NUnit, and all kinds of exciting .NET technologies. He started C# City in order to accelerate his .NET learning.
This entry was posted in Libraries, Web and tagged , , . Bookmark the permalink.

Leave a Reply

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