3

As far as I can tell, there are 3 ways to create a DropDownList in an ASP.NET MVC View:

  1. Hand code the HTML manually
  2. <asp:DropDownList ID="someID" runat="server"></asp:DropDownList>
  3. <%= Html.DropDownList("someID") %>

I think we can all agree that #1 is (generally) a waste of time.

With #2, it appears to be the "WebForms" way of doing it, but has an advantage in that if you're writing a View you can have access to the object you've created via inline code that occurs after it. For example:

<asp:DropDownList ID="someID" runat="server"></asp:DropDownList>
<% 
   someID.SelectedIndex = 0;  
   string someString = someID.SelectedValue.ToString();
%>

This does not appear to be possible with #3.

The nice thing that I've discovered about #3 (the HTML Helper way) is that by passing it a string, it sets the Name and ID to the string as well as uses the string to search the ViewData dictionary and auto-generate the respective tags for the DropDownList based on the SelectList that was added to the ViewData dictionary that was added in the calling Controller.

// controller code
ViewData["someID"] = new SelectList(someMethod().ToList());  

For the life of me, I cannot figure out if there is a way to auto-generate the tags with <asp:DropDownList> or if I have to manually create them myself.

What's generally the best approach for implementing a DropDownList in ASP.NET MVC?

2
  • <asp:[controlType]> should never be used in MVC. Jul 30, 2010 at 15:10
  • Care to elaborate? It's not that I don't believe you, but I want to understand why.
    – Pretzel
    Jul 30, 2010 at 15:19

1 Answer 1

1
<%= Html.DropDownList("name", new SelectList(someEnumerable, "valueProperty", "textProperty")) %>

where someEnumerable is a property on your viewModel.

for example:

class Person
{
    int id;
    string name;
}

class myVM
{
    IEnumerable<Person> people;
}

<%= Html.DropDownList("name", new SelectList(Model.people, "id", "name")) %>

Edit dont make the SelectList in your controller, this is view specific code and belongs in the view, just send your IEnumerable in the viewmodel.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.