2013-02-18 94 views
1

我有一個列表,我想在下拉框中填充此列表。下拉列表中的列表項

來自控制器:

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

     } 

從視圖中:

@Html.DropDownListFor(..... // NOW HOW CAN I DISPLAY THE VALUES IN THE DROPDOWNLIST ? 
+0

作爲@Xander指出,你可以自己做。閱讀此鏈接:http://stackoverflow.com/questions/5885627/using-html-dropdownlistfor-with-a-selectlist Viewbag是一個例子。但是您仍然希望將模型傳遞迴您的視圖並將其下拉列表綁定到它 – 2013-02-18 21:23:30

回答

0

控制器

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

視圖

@Html.DropDownList("humans", Model as SelectList) 
0

您應該先定義一個模型類型。

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)