Ajax异步调用Controller的Return JsonResult生成下拉列表

时间:2023-03-08 17:19:15
Ajax异步调用Controller的Return JsonResult生成下拉列表
 @using System.Web.Optimization;
@{
Layout = null;
} <!DOCTYPE html> <html>
<head>
<meta name="viewport" content="width=device-width" />
<title></title>
<script src="~/css/jquery-1.7.1.js"></script>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery.get("/FruitCategory/SelectLists", null, function (ruselt) {
jQuery("#category").empty().append(jQuery("<option/>", {
value: 0,
text: "请选择..."
}));
//jQuery.each(ruselt, function (index, item) {
// jQuery("#category").append(jQuery("<option/>", {
// value: item.Value,
// text: item.Text
// }));
//})
jQuery.each(ruselt, function (index,item) {
jQuery("#category").append(jQuery("<option/>")
.attr("value", item.Value)
.text(item.Text)); })
})
})
</script>
</head>
<body>
<div id="Div_1">
<select id="category" class="category">
</select>
</div>
</body>
</html>

FruitCategoryEntity.cs

       //public List<SelectListItem> GetAll()
//{
// List<SelectListItem> items = new List<SelectListItem>();
// DataTable dt = SQLHelper.ExecuteDataSet(SQLHelper.ConnectionStringLocalTransaction, CommandType.StoredProcedure, "usp_FruitCategory_GetAll", null).Tables[0];
// foreach (DataRow dr in dt.Rows)
// {
// items.Add(new SelectListItem
// {
// Text = dr.Field<string>("CategoryName"),
// Value = dr.Field<int>("FruitCategory_nbr").ToString()
// });
// }
// return items;
//} public IEnumerable<SelectListItem> GetAll()
{
DataTable dt = SQLHelper.ExecuteDataSet(SQLHelper.ConnectionStringLocalTransaction, CommandType.StoredProcedure, "usp_FruitCategory_GetAll", null).Tables[];
IEnumerable<SelectListItem> items = dt.AsEnumerable().Select(Row => new SelectListItem()
{
Text = Row.Field<string>("CategoryName"),
Value = Row.Field<int>("FruitCategory_nbr").ToString()
});
return items;
}

FruitCategoryController.cs 控制器

         public ActionResult SelectList()
{
return View();
}
public JsonResult SelectLists()
{
IEnumerable<SelectListItem> list = objFruitCategoryEntity.GetAll();
return Json(list, JsonRequestBehavior.AllowGet);
}