asp.net-mvc 使用 MVC 使用 List<string> 填充 @Html.DropDownList

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6333270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:15:37  来源:igfitidea点击:

Populate @Html.DropDownList with a List<string> using MVC

asp.net-mvcasp.net-mvc-3drop-down-menuhtml-select

提问by wardh

I'm trying to populate a @Html.DropDownList with a List using MVC and Razor. Bellow is my code for the controller. So I need to pick the list out of my ViewBag and fill the dropdownlist.

我正在尝试使用 MVC 和 Razor 使用列表填充 @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();
    }

Thanks for the help.

谢谢您的帮助。

回答by Ethan Cabiac

If this is in an Editor for your model property:

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

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

回答by Meghs Dhameliya

//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();
}

回答by kunal gupta

value is not getting saves in the database..please see where i am getting mistake...

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

    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();
        }