MVC CORE新增DropDownListFor的做法

MVC CORE新增DropDownListFor的做法

基本上有2種做法

第1種-是在cshtml上直接做

第2種-是寫在controller中,用ViewBag帶到網頁中

如果是寫在controller,也可用ViewBag去讀取資料庫的項目,做動態的下拉選單

(相關的資料表、model都要先新增完成)

 

code:

在cshtml

@{
    ViewData["Title"] = "Create";
    
    List<SelectListItem> listItems= new List<SelectListItem>();
    listItems.Add(new SelectListItem
        {
            Text = "ITEM-1",
            Value = "ITEM-1"
        });
    listItems.Add(new SelectListItem
        {
            Text = "ITEM-2",
            Value = "ITEM-2"           
        });
    listItems.Add(new SelectListItem
        {
            Text = "ITEM-3",
            Value = "ITEM-3"
        });
    }


--
@Html.DropDownListFor(model => model.DEP, listItems, "請選擇")

 

在controller

//Controllers

public IActionResult Create()
        {           

            var selectList = new List<SelectListItem>()
            {
                new SelectListItem {Text="text-1", Value="value-1" },
                new SelectListItem {Text="text-2", Value="value-2" },
                new SelectListItem {Text="text-3", Value="value-3" },
            };

            //預設選擇哪一筆
            selectList.Where(q => q.Value == "value-2").First().Selected = true;

            ViewBag.SelectList = selectList;


            return View();
        }

//cshtml

 @Html.DropDownListFor(model => model.DEP, new SelectList(ViewBag.selectList,"Value","Text"))

 

ViewBag去讀取資料庫的項目

List<QUESTIONDEP> QUESTIONDEPLIST = new List<QUESTIONDEP>();
QUESTIONDEPLIST = (from QUESTIONDEP in _context.QUESTIONDEP select QUESTIONDEP).ToList(); 
ViewBag.QUESTIONDEPLIST = QUESTIONDEPLIST.Select(c => new SelectListItem { Value = c.DEPID, Text = c.DEPNAME }).ToList();

 

 

自我LV~