使用MVC </string>使用List <string>填充@ Html.DropDownList

时间:2011-06-13 16:26:45

标签: asp.net-mvc asp.net-mvc-3 drop-down-menu html-select

我正在尝试使用MVC和Razor填充带有List的@ Html.DropDownList。 贝娄是我的控制器代码。所以我需要从ViewBag中选择列表并填写下拉列表。

public ActionResult Register()
    {
        sparklingEntities context = new sparklingEntities();
        var query = (from discs in context.Disciplines
                     select discs).ToList();
        List<string> listOfDiscs = new List<string>();
        foreach (var item in query)
        {
            listOfDiscs.Add(item.Discipline);
        }
        ViewBag.ListOfDisciplines = listOfDiscs;
        return View();
    }

感谢您的帮助。

3 个答案:

答案 0 :(得分:11)

如果这是在您的模型属性的编辑器中:

@Html.DropDownList("", new SelectList(ViewBag.ListOfDisciplines, Model))

答案 1 :(得分:1)

//Increase performance by Eliminating foreach loop!
public ActionResult Register()
{
    sparklingEntities context = new sparklingEntities();
    var query = (from discs in context.Disciplines
                 select discs.Discipline); // change this line as discs.Discipline
    ViewBag.ListOfDisciplines = listOfDiscs;
    return View();
}

答案 2 :(得分:0)

值没有在数据库中保存。请查看我在哪里弄错了...

    public ActionResult Role(Role_Master_Table t)
    {
        FTSdatabaseEntities dc = new FTSdatabaseEntities();
        {

            //ViewBag.Status_Description = new SelectList(dc.Status_Master_Table, "StatusId", "Status_Description", "Remarks");
            var query = (from Status_Description in dc.Status_Master_Table
                         select Status_Description).ToList();
            List<string> listOfDiscs = new List<string>();
            foreach (var item in query)
            {
                listOfDiscs.Add(t.Status);
                dc.Role_Master_Table.Add(t);
                dc.SaveChanges();

            }
            ViewBag.Status_Description = listOfDiscs;


            return View();
        }