如何在MVC的GetAllEmpDetails视图实现下拉框联动加载员工数据
解决MVC下拉框切换时加载对应状态员工数据的问题
问题场景
使用C# + ADO.NET开发MVC Web应用,需求为:下拉框选择「Pending Request」时显示EmployeeStatus=1的员工,选择「Done Request」时显示EmployeeStatus=2的员工,但目前下拉框索引变化时无法加载对应数据。
实现步骤
1. 前端视图修改(GetAllEmpDetails.cshtml)
给下拉框添加切换事件,通过AJAX请求动态更新员工列表:
下拉框与列表容器
<!-- 状态筛选下拉框 --> <select id="statusFilter" class="form-control"> <option value="0">All Requests</option> <option value="1">Pending Request</option> <option value="2">Done Request</option> </select> <!-- 员工列表容器,用于动态替换内容 --> <div id="employeeListContainer"> <!-- 初始服务器渲染的员工列表 --> @foreach (var emp in Model) { <div class="employee-card"> <p>@emp.EmployeeName</p> <p>Status: @(emp.EmployeeStatus == 1 ? "Pending" : "Done")</p> <!-- 其他员工信息字段 --> </div> } </div>
AJAX交互脚本
<script src="~/Scripts/jquery-3.6.0.min.js"></script> <script> $(function() { // 下拉框切换时触发请求 $("#statusFilter").on("change", function() { const selectedStatus = $(this).val(); $.ajax({ url: '@Url.Action("GetEmployeesByStatus", "Employee")', type: "GET", data: { status: selectedStatus }, success: function(data) { // 清空容器并渲染新数据 $("#employeeListContainer").empty(); if (data.length === 0) { $("#employeeListContainer").html("<p>No employees matched the selected status.</p>"); return; } data.forEach(emp => { const statusText = emp.EmployeeStatus === 1 ? "Pending" : "Done"; const empHtml = ` <div class="employee-card"> <p>${emp.EmployeeName}</p> <p>Status: ${statusText}</p> </div> `; $("#employeeListContainer").append(empHtml); }); }, error: function() { alert("Failed to load employee data."); } }); }); }); </script>
2. 控制器新增Action方法
在对应控制器(如EmployeeController)中添加处理AJAX请求的Action,返回JSON格式的员工数据:
public ActionResult GetEmployeesByStatus(int status) { var empRepo = new EmployeeRepository(); List<EmployeeModel> employees; if (status == 0) { // 加载所有员工 employees = empRepo.GetAllEmployees(); } else { // 根据状态过滤员工 employees = empRepo.GetEmployeesByStatus(status); } return Json(employees, JsonRequestBehavior.AllowGet); }
3. 完善Repository层方法
确保Repository中有根据状态查询员工的方法,调用对应存储过程:
public List<EmployeeModel> GetEmployeesByStatus(int status) { var empList = new List<EmployeeModel>(); using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["YourConnString"].ConnectionString)) { var cmd = new SqlCommand("GetEmployeesByStatus", con) { CommandType = CommandType.StoredProcedure }; cmd.Parameters.AddWithValue("@Status", status); con.Open(); var dr = cmd.ExecuteReader(); while (dr.Read()) { empList.Add(new EmployeeModel { EmployeeId = Convert.ToInt32(dr["EmployeeId"]), EmployeeName = dr["EmployeeName"].ToString(), EmployeeStatus = Convert.ToInt32(dr["EmployeeStatus"]) // 映射其他字段 }); } con.Close(); } return empList; }
4. 确保存储过程正确
存储过程GetEmployeesByStatus需根据传入的@Status参数过滤数据:
CREATE PROCEDURE GetEmployeesByStatus @Status INT AS BEGIN SELECT EmployeeId, EmployeeName, EmployeeStatus, -- 其他字段 FROM Employees WHERE EmployeeStatus = @Status END
内容的提问来源于stack exchange,提问作者ahmed barbary
相关产品推荐
相关产品推荐

