我想通过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);
}
最后,我想在下拉列表中显示它以便动态显示,但我该怎么做。
答案 0 :(得分:0)
这是一个简单的演示:
1.View(Index.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.Controller:
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。结果: