I've recently started a new ASP.NET MVC project and ran across what is a really common need: I wanted a drop-down list that contained the same items but that I could re-use a few times on the same page. In "classic" ASP.NET I'd just create a user control, expose a property or two to allow me to handle data binding to this list and be done with it. Heck, in my case it didn't even need to be data driven - it was a static list of items (like a drop-down list of states). I could do this inside of a view then populate the list but I didn't want to tie this to a particular view, I wanted it available from any page.OK, so how do you do this in ASP.NET MVC? It doesn't have the same control model, so I wasn't entirely sure what the best way to handle this was.Some things I considered:Create my own "helper" that generated all the HTML for it. That sounded like way more work than I wanted to do.Create my own helper but somehow leverage the built-in DropDownList to do the heavy lifting. I started looking at this, didn't see immediately how I would hook everything together so I skipped it.Create a partial view. This was actually my first thought but I couldn't figure out how I'd handle being able to "name" the DropDownList in the partial view (since I needed to have multiple copies of the control on the same page and I wanted each to have it's own unique name and bind to a different property in my ViewModel. Mind you, at this point I have like 3 hours experience with MVC. Honestly, I wasn't happy with any of them. They all seemed like more work than I was expecting (but at this point I wasn't sure how much work was really required). I did a bunch of Google searches and finally ran across this question on Stack Overflow:http://stackoverflow.com/questions/289048/asp-net-mvc-us-state-drop-down-listThat was exactly what I was looking for. You create a simple static method that returns an IDictionary and then another one which returns a SelectList of your IDictionary so that it can be used by the framework.public class ItemScores{ publicstaticreadonlyIDictionary<string, string> Scores = newDictionary<string, string>() { {"5 - Best", "1"}, {"4", "4"}, {"3 - Average", "3"}, {"2", "2"}, {"1 - Bad", "1"} }; publicstatic SelectList ScoreList { get { returnnew SelectList(Scores, "Value", "Key"); } }}Then from within your view you use the standard Html helper: <%: Html.DropDownList("OverallScore", ItemScores.ScoreList) %>
That was a lot closer to what I was expecting. I expect to revisit this topic again as soon as I need a slightly more complex component, but for right now this works well for me.