需要一些关于下一个场景的正确方法的建议。
我有三个模型类:
namespace App.Models
{
public partial class Company
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
}
public partial class Department
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public int CompanyID { get; set; }
public Company Company { get; set; };
}
public partial class User
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public int Department { get; set; }
public Department Department { get; set; };
}
}
当我访问
UserController
的创建视图时,我有一个组合框来选择 DepartmentID
。
问题是列表太大了。我想在视图中添加一个列表来选择
Company
。在 Department
组合框中,仅应显示所选 Department
中的 Company
。
关于实现这一目标的正确方法有什么建议吗?我已经知道如何在视图包中按
Department
过滤 Company
。
但我不知道如何在视图中进行更改并将过滤器发送到控制器。
提前致谢。
关于实现这一目标的正确方法有什么建议吗?我已经知道如何 在视图包中按公司过滤部门。
但我不知道如何在视图中进行更改并发送 过滤到控制器
好吧,首先将您的公司加载到您的视图中。您需要做的就是查询您的公司对象并将其绑定到 ViewBag 中。您可以执行以下操作:
ViewBag.Companies = _context.Companies.ToList();
在视图中,您应该有以下代码:
<div class="form-group">
<label asp-for="CompanyId" class="control-label"></label>
<select asp-for="CompanyId" class="form-control" onchange="getDepartments(this.value)">
<option value="">Select Company</option>
@foreach (var company in ViewBag.Companies)
{
<option value="@company.ID">@company.Name</option>
}
</select>
</div>
现在,为了根据所选公司加载部门,您应该获取公司 Id,然后调用 API 以根据传递的公司 Id 获取部门。使用ajax请求来实现。
您可以执行以下操作:
<div class="form-group">
<label asp-for="DepartmentId" class="control-label"></label>
<select asp-for="DepartmentId" id="departmentDropdown" class="form-control">
<option value="">Select Department</option>
</select>
</div>
脚本:
<script>
function getDepartments(companyId) {
$.ajax({
url: '/User/GetDepartments',
type: 'GET',
data: { companyId: companyId },
success: function (data) {
$('#departmentDropdown').empty();
$.each(data, function (i, department) {
$('#departmentDropdown').append($('<option>').text(department.name).attr('value', department.id));
});
}
});
}
</script>
控制器:
public IActionResult GetDepartments(int companyId)
{
var departments = _context.Departments.Where(d => d.CompanyID == companyId).ToList();
return Json(departments);
}
注意: 确保您的ajax请求URL相应地指向您的控制器。