# asp.net mvc 動態產生下拉選單的方法 ###### tags: `程式設計` ## 範例程式碼 https://dotnetfiddle.net/AHKPyj ![](https://i.imgur.com/YV80bqZ.png) ## 原理 利用 SelectListItem 的物件,做一個 ```List<SelectListItem>```,讓 ViewBag 帶去 View 的畫面 (也可以放在Viemodel) ## Controller ```=C# List<news_group> newsgroup = db.news_group.ToList(); ViewBag.newsgroup = newsgroup.Select(data => new SelectListItem { Text = data.groupName, Value = data.groupName }).ToList(); ``` ## View ```=C# @{ List<SelectListItem> group_items = (List<SelectListItem>)ViewBag.newsgroup;} @Html.DropDownList("group", group_items, "請下拉選擇", new { @class = "form-control" }) ``` 註:上面最後一行**group**就會是產出來的select的name
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up