1 @using System.Web.Optimization; 2 @{ 3 Layout = null; 4 } 5 6 <!DOCTYPE html> 7 8 <html> 9 <head> 10 <meta name="viewport" content="width=device-width" /> 11 <title></title> 12 <script src="~/css/jquery-1.7.1.js"></script> 13 <script type="text/javascript"> 14 jQuery(document).ready(function () { 15 jQuery.get("/FruitCategory/SelectLists", null, function (ruselt) { 16 jQuery("#category").empty().append(jQuery("<option/>", { 17 value: 0, 18 text: "请选择..." 19 })); 20 //jQuery.each(ruselt, function (index, item) { 21 // jQuery("#category").append(jQuery("<option/>", { 22 // value: item.Value, 23 // text: item.Text 24 // })); 25 //}) 26 jQuery.each(ruselt, function (index,item) { 27 jQuery("#category").append(jQuery("<option/>") 28 .attr("value", item.Value) 29 .text(item.Text)); 30 31 }) 32 }) 33 }) 34 </script> 35 </head> 36 <body> 37 <div id="Div_1"> 38 <select id="category" class="category"> 39 </select> 40 </div> 41 </body> 42 </html>
FruitCategoryEntity.cs
1 //public List<SelectListItem> GetAll() 2 //{ 3 // List<SelectListItem> items = new List<SelectListItem>(); 4 // DataTable dt = SQLHelper.ExecuteDataSet(SQLHelper.ConnectionStringLocalTransaction, CommandType.StoredProcedure, "usp_FruitCategory_GetAll", null).Tables[0]; 5 // foreach (DataRow dr in dt.Rows) 6 // { 7 // items.Add(new SelectListItem 8 // { 9 // Text = dr.Field<string>("CategoryName"), 10 // Value = dr.Field<int>("FruitCategory_nbr").ToString() 11 // }); 12 // } 13 // return items; 14 //} 15 16 public IEnumerable<SelectListItem> GetAll() 17 { 18 DataTable dt = SQLHelper.ExecuteDataSet(SQLHelper.ConnectionStringLocalTransaction, CommandType.StoredProcedure, "usp_FruitCategory_GetAll", null).Tables[0]; 19 IEnumerable<SelectListItem> items = dt.AsEnumerable().Select(Row => new SelectListItem() 20 { 21 Text = Row.Field<string>("CategoryName"), 22 Value = Row.Field<int>("FruitCategory_nbr").ToString() 23 }); 24 return items; 25 }
FruitCategoryController.cs 控制器
1 public ActionResult SelectList() 2 { 3 return View(); 4 } 5 public JsonResult SelectLists() 6 { 7 IEnumerable<SelectListItem> list = objFruitCategoryEntity.GetAll(); 8 return Json(list, JsonRequestBehavior.AllowGet); 9 }