ASP.NET MVC: DropDownList - From a DataSource, SelectedItem and Native Code Access in a View

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

  • Manual HTML code manually
  • <asp:DropDownList ID="someID" runat="server"></asp:DropDownList>
  • <%= Html.DropDownList("someID") %>

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

C # 2 seems to be the “WebForms” method, but it has the advantage that if you write View, you can access the object that you created using the inline code that comes up after This. For instance:

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

This is not possible with C # 3.

, # 3 ( HTML-), , , , , ViewData - DropDownList SelectList, ViewData, .

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

, <asp:DropDownList> .

, DropDownList ASP.NET MVC?

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

someEnumerable Model.

:

class Person
{
    int id;
    string name;
}

class myVM
{
    IEnumerable<Person> people;
}

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

. SelectList , , IEnumerable .

+1

Source: https://habr.com/ru/post/1757365/


All Articles