asp.net-mvc - Asp.net 核心 - 通过 Ajax 调用填充下拉列表
问题描述
我想通过ajax调用将我的数据从SQL显示到下拉列表,你能帮我怎么做吗?如何在控制器中选择特定的列名。
//This is my Model
public class ErrorCategory
{
[Key]
public int Eid { get; set; }
public string ErrorDescription { get; set; }
}
//My dataAccessLayer
public class ErrorDataAccessLayer
{
readonly string connectionString = ConnectionString.CName;
public IEnumerable<ErrorCategory> GetAllError()
{
List<ErrorCategory> lstError = new List<ErrorCategory>();
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("spGetAllErrorCategory", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
ErrorCategory error = new ErrorCategory();
error.Eid = Convert.ToInt32(rdr["Eid"]);
error.ErrorDescription = rdr["ErrorDescription"].ToString();
lstError.Add(error);
}
con.Close();
}
return lstError;
}
}
//My Controller
public IActionResult GetErrorCategory()
{
IEnumerable<ErrorCategory> error = errorDataAccessLayer.GetAllError();
return new JsonResult(error);
}
最后,我想在下拉列表中显示它以便动态,但我该怎么做。
解决方案
这是一个简单的演示:
1.查看(索引.cshtml):
<select id="list" ></select>
@section Scripts{
<script>
$(document).ready(function () {
$.ajax({
method: "GET",
url: "Home/GetJson",
dataType: "json",
success: function (data) {
var s = '<option value="-1">Please select one</option>';
console.log(data);
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].eid + '">' + data[i].errorDescription + '</option>';
}
$("#list").html(s);
}
})
})
</script>
}
2.控制器:
public IActionResult Index()
{
return View();
}
public IActionResult GetJson()
{
IEnumerable<ErrorCategory> error = new List<ErrorCategory>()
{
new ErrorCategory(){ Eid=1,ErrorDescription="aa"},
new ErrorCategory(){ Eid=2,ErrorDescription="bb"},
new ErrorCategory(){ Eid=3,ErrorDescription="cc"}
};
return new JsonResult(error);
}
3.结果:
推荐阅读
- c++ - Poco C++ 抽象配置搜索属性的所有键
- python - 执行一系列链接的脚本
- node.js - 如何通过 URL db-migrate 到 Heroku 上的另一个 postgres
- c++ - C++:复制对象类型指针
- javascript - getServerSideProps 不使用导入更新数据
- r - 如何从 PCA 中删除分数?
- python - 如果高度不足以容纳使用 matplotlib bar_label 辅助函数的标签,如何防止标签
- excel - 将多个 Excel 工作表范围转换为 PDF VBA
- node.js - Docker 的“彩色输出”在 Github Actions 上失败
- php - 从 CSV 获取对象数组,删除标题并更改键