MVC Html辅助方法DropDownList的简单使用、连接MYSQL数据库用自定义model类接收
附上启发链接:https://www.cnblogs.com/CreateMyself/p/5424894.html
[HttpGet] public ActionResult Edit(int id) { var db = Congfig.MySqlConn; const string sql = "SELECT S,W FROM SW"; var result = db.ExecuteDataReader(sql); MySqlConnection con = new MySqlConnection("server=012.345.678.910;port=0123;User Id=UserId;password=Pwd;database=DB"); MySqlDataAdapter da = new MySqlDataAdapter(sql, con); DataSet ds = new DataSet(); da.Fill(ds); DataTable dt = ds.Tables[0]; #region //从数据库中读取 var categoryList = new List<BlogCategory>(); for (int i = 0; i < dt.Rows.Count; i++) { categoryList.Add(new BlogCategory() { CategoryId = dt.Rows[i][0].ToString(), CategoryName = dt.Rows[i][1].ToString() }); } var selectItemList = new List<SelectListItem>() { //new SelectListItem(){Value="0",Text="全部",Selected=true} }; var selectList = new SelectList(categoryList, "CategoryId", "CategoryName"); selectItemList.AddRange(selectList); ViewBag.database = selectItemList; #endregion var model = Curd.GetModel<Users>(id); ViewBag.Msg = Msg; Msg = ""; return View(model); } #region public class BlogCategory { public string CategoryId { get; set; } public string CategoryName { get; set; } } #endregion
<div class="form-group marginB"> <label class="col-sm-1 control-label">设置管理区域</label> <div class="col-sm-8"> @Html.DropDownList("database-dropdownlist", (ViewBag.database as IEnumerable<SelectListItem>)@*, new { @class = "btn btn-success dropdown-toggle form-control" }*@) </div> </div>
效果图: