从SQL Server查询填充Razor中的下拉列表
我是CDC的数据库管理员。我创建了一个web应用程序来显示SQL Server数据库中的信息,我的经理希望我把它放在一个Razor页面上。此应用程序使用下拉列表供用户选择参数以选择数据。我试图填充数据库中的下拉列表,以保持参数的最新状态,但我无法做到这一点。我在网上找到的所有东西都试过了,但都不走运。这是我最后一次尝试:从SQL Server查询填充Razor中的下拉列表,sql,sql-server,asp.net-core,Sql,Sql Server,Asp.net Core,我是CDC的数据库管理员。我创建了一个web应用程序来显示SQL Server数据库中的信息,我的经理希望我把它放在一个Razor页面上。此应用程序使用下拉列表供用户选择参数以选择数据。我试图填充数据库中的下拉列表,以保持参数的最新状态,但我无法做到这一点。我在网上找到的所有东西都试过了,但都不走运。这是我最后一次尝试: public IActionResult Index(string DeptId, string DeptName) { ViewBag.Message
public IActionResult Index(string DeptId, string DeptName)
{
ViewBag.Message = "Department Id: " + DeptId;
ViewBag.Message += "\\ | Department Name: " + DeptName;
ViewBag.Departments = GetDepartmentDetails();
return View();
}
private static List<Department> GetDepartmentDetails()
{
string constr = @"Data Source=COREPROGRAMM;Initial Catalog=Employees;uid=sa;password=*********";
List<Department> departments = new List<Department>();
using (SqlConnection con = new SqlConnection(constr))
{
string query = "SELECT DeptName, DeptId FROM Department";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
departments.Add(new Department
{
DeptId = Convert.ToInt32(sdr["DeptId"]),
DeptName = sdr["DeptName"].ToString(),
});
}
}
con.Close();
}
}
return departments;
}
@{
ViewData["Title"] = "Home Page";
}
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
function SetDept() {
$("#DeptName").val($("#ddlDept option:selected").text());
}
</script>
@if (ViewBag.Message != null)
{
<script type="text/javascript">
$(function () {
$("#divData").empty().html('@ViewBag.Message');
});
</script>
}
<form method="post" asp-controller="Home" asp-action="Index">
<input type="hidden" name="DeptName" id="DeptName" />
<div class="row">
<div class="col-md-5">
<select id="ddlDept" name="DeptId" asp-for="DeptId" asp-items="@(new SelectList(ViewBag.Departments,"DeptId","DeptName"))" class="form-control" onchange="SetDept()">
<option value="0">Please select Department</option>
</select>
</div>
<input type="submit" value="Submit" class="btn btn-primary" />
</div>
<div class="row mt-5 ml-5" id="divData"></div>
非常感谢您的帮助。Hi@Donald,您收到的错误消息是什么?你的意思是你不能在你的视图中填充dropdownlist吗?它没有给我一个错误。我试图在加载页面时填充下拉列表,但它似乎没有调用索引函数。