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); // select the fourth item
// Solution #2
Post posts = ...
post selected = posts; // or set somewhere else
s = new SelectList(posts, selected)