Asp.net mvc ASP.NET MVC:DropDownList——视图中的DataSource、SelectedItem和内联代码访问

Asp.net mvc ASP.NET MVC:DropDownList——视图中的DataSource、SelectedItem和内联代码访问,asp.net-mvc,drop-down-menu,html-helper,selectlist,Asp.net Mvc,Drop Down Menu,Html Helper,Selectlist,据我所知,有3种方法可以在ASP.NET MVC视图中创建DropDownList: 手工编写HTML代码 我想我们都同意,1(通常)是浪费时间 使用#2,这似乎是一种“WebForms”方式,但有一个优势,即如果您正在编写视图,您可以通过在它之后出现的内联代码访问您创建的对象。例如: <asp:DropDownList ID="someID" runat="server"></asp:DropDownList> <% someID.SelectedIn

据我所知,有3种方法可以在ASP.NET MVC视图中创建DropDownList:

  • 手工编写HTML代码
  • 我想我们都同意,1(通常)是浪费时间

    使用#2,这似乎是一种“WebForms”方式,但有一个优势,即如果您正在编写视图,您可以通过在它之后出现的内联代码访问您创建的对象。例如:

    <asp:DropDownList ID="someID" runat="server"></asp:DropDownList>
    <% 
       someID.SelectedIndex = 0;  
       string someString = someID.SelectedValue.ToString();
    %>
    
    class Person
    {
        int id;
        string name;
    }
    
    class myVM
    {
        IEnumerable<Person> people;
    }
    
    <%= Html.DropDownList("name", new SelectList(Model.people, "id", "name")) %>
    
    就我的一生而言,我不知道是否有办法使用
    自动生成标记,或者是否必须自己手动创建标记

    在ASP.NET MVC中实现DropDownList的最佳方法通常是什么?

    
    
    <%= Html.DropDownList("name", new SelectList(someEnumerable, "valueProperty", "textProperty")) %>
    
    其中someEnumerable是viewModel上的属性

    例如:

    <asp:DropDownList ID="someID" runat="server"></asp:DropDownList>
    <% 
       someID.SelectedIndex = 0;  
       string someString = someID.SelectedValue.ToString();
    %>
    
    class Person
    {
        int id;
        string name;
    }
    
    class myVM
    {
        IEnumerable<Person> people;
    }
    
    <%= Html.DropDownList("name", new SelectList(Model.people, "id", "name")) %>
    
    班级人员
    {
    int-id;
    字符串名;
    }
    类myVM
    {
    无数人;
    }
    

    编辑不要在控制器中创建SelectList,这是特定于视图的代码,属于视图,只需在viewmodel中发送IEnumerable即可。

    不应在MVC中使用。是否要详细说明?不是我不相信你,而是我想知道为什么。