开发者

ASP.NET MVC: DropDownList -- Of DataSource, SelectedItem, and inline code access within the View

开发者 https://www.devze.com 2023-01-09 19:44 出处:网络
As far as I can tell, there are 3 ways to create a DropDownList in an ASP.NET MVC View: Hand code the HTML manually

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开发者_JAVA技巧 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?


<%= 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

精彩评论

暂无评论...
验证码 换一张
取 消