C# 在下拉列表中列出项目

C# 在下拉列表中列出项目,c#,asp.net-mvc,html-helper,C#,Asp.net Mvc,Html Helper,我有一个列表,我想在下拉框中填充这个列表 从控制器: public ActionResult Index() { List<SelectListItem> hum = allHuman(); return View(); } 控制器 var list = new SelectList(allHuman(), "Id", "Name"); 看法 您应该首先定义模型类型 class MyViewMode

我有一个列表,我想在下拉框中填充这个列表

从控制器:

public ActionResult Index()
        {
            List<SelectListItem> hum = allHuman();
            return View();

        }
控制器

var list = new SelectList(allHuman(), "Id", "Name");
看法


您应该首先定义模型类型

class MyViewModel
{
    // I assume you will use this property to read the selected value 
    public string Human {get;set;}

    //dropdown values
    public List<SelectListItem> AllHumans {get;set;}
}
然后可以在视图中显示它:

@model MyViewModel

@Html.DropDownListFor(model => model.Human, Model.AllHumans, null)

正如@Xander所指出的,你可以自己做这件事。阅读此链接:Viewbag就是一个例子。但是您仍然需要将模型传递回视图,并将DropDownList for绑定到它
class MyViewModel
{
    // I assume you will use this property to read the selected value 
    public string Human {get;set;}

    //dropdown values
    public List<SelectListItem> AllHumans {get;set;}
}
public ActionResult Index()
{
    var model = new MyViewModel { AllHumans  =  allHuman()};
    return View(model);
}
@model MyViewModel

@Html.DropDownListFor(model => model.Human, Model.AllHumans, null)