[MVC4-基礎] 從資料庫取值顯示在DropDownList中

时间:2023-03-09 07:48:46
[MVC4-基礎] 從資料庫取值顯示在DropDownList中

剛開始學MVC4,以下是一些基礎的學習筆記!


完成效果像下面這樣,資料來源是既有的Database。

[MVC4-基礎] 從資料庫取值顯示在DropDownList中

1.Controller

public ActionResult Index()
{ SqlConnection DbErp = new SqlConnection(ErpString); //創建資料庫連線
SqlCommand cmd = new SqlCommand("select dep,name from dept",DbErp); //輸入SQL命令
DbErp.Open(); //開啟資料庫連線 var reader = cmd.ExecuteReader(); //取出結果集 List<SelectListItem> depts = new List<SelectListItem>(); while(reader.Read()){ //逐筆讀出資料寫入List
//(0)=dep ; (1)=name
depts.Add(new SelectListItem { Text = reader.GetString(), Value = reader.GetString()});
} DbErp.Close(); //關閉資料庫連線 ViewBag.DeptType = depts; return View();
}

2.View

<h2>維修申請單</h2>

<p>
@Html.Label("DeptType","申請部門")
@Html.DropDownList("DeptType")
</p>