public List<SelectListItem> see() { string a = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; SqlConnection conn =new SqlConnection(a); conn.Open(); string sql = "spii"; SqlCommand cmd = new SqlCommand(sql,conn); SqlDataReader dr = cmd.ExecuteReader(); List<SelectListItem> yui = new List<SelectListItem>(); for (int i = 0; i <=dr.FieldCount+1; i++) { dr.Read(); yui.Add(new SelectListItem() { Text = dr[1].ToString(), Value = dr[0].ToString(), Selected = dr[0].Equals(3) }); } dr.Close(); cmd.Dispose(); conn.Close(); conn.Dispose(); return yui; }
接著利用List
回到Controll那邊:
Model ty = new Model(); public ActionResult Index() { ViewBag.select1 = ty.see(); ViewBag.select2 = ty.see(); }
再回到View:
@Html.ListBox("select1", null, new { id="SelectList2",size="2"})
@Html.DropDownList("select2",null ,new { id="Select2"})
大功告成!!
沒有留言:
張貼留言