我创建了一个包含两个实体的视图模型。我将此视图模型传递给我的MVC Razor视图,该视图分别为每个实体提供了两个html下拉列表。
<select class="form-control" id="Employees" name="Employees">
@foreach (var employee in Model.Employees)
{
<option value="@employee.Id"> @employee.name </option>
}
</select>
<select class="form-control" id="Tasks" name="Tasks">
@foreach (var task in Model.Tasks)
{
<option value="@task.Id"> @task.name </option>
}
</select>
Employee表是Task表的父表。我想要的是获得与特定员工相关的所有任务。例如在Employee下拉列表中,我选择John,然后在Tasks下拉列表中,我应该获得与John相关的所有任务。我知道如何用ajax做到这一点。我正在寻找其他解决方案。
是否可以做这样的事情:
@foreach (var task in Model.Tasks.Where(x=>x.employeeId == 'Selected in previous dropdown'))
{
<option value="@task.Id"> @task.name </option>
}
答案 0 :(得分:0)
Html块
<select id="Employees">
<option value="">Select Employee</option>
<option value="1">Employee1</option>
<option value="2">Employee2</option>
</select>
<select id="Tasks">
<option value="">Select Task</option>
<option value="1" data-employee="1">Employee1Task1</option>
<option value="2" data-employee="1">Employee1Task2</option>
<option value="3" data-employee="1">Employee1Task3</option>
<option value="1" data-employee="2">Employee2Task1</option>
<option value="2" data-employee="2">Employee2Task2</option>
<option value="3" data-employee="2">Employee2Task3</option>
</select>
脚本场景
<script>
$(document).ready(function () {
//on page ready hide all task option
$("#Tasks").find('option').hide();
// set task as empty
$("#Tasks").val('');
// onchange of employee Drop down
$("#Employees").on('change', function () {
var selectedEmployee = $("#Employees").val();
if (selectedEmployee != '') {
$("#Tasks").find('option').hide();
$("#Tasks option[value='']").show();
$('*[data-employee="' + selectedEmployee + '"]').show();
}
else {
// if employee not selected then hide all tasks
$("#Tasks").find('option').hide();
$("#Tasks").val('');
}
});
});
</script>
请使用MVC方式为每个循环填充国家/地区下拉列表并使用上面的脚本。强制性的情况是你必须渲染所有级联选项
<select class="form-control" id="Employees" name="Employees">
@foreach (var employee in Model.Employees)
{
<option value="@employee.Id"> @employee.name </option>
}
</select>
<select class="form-control" id="Tasks" name="Tasks">
@foreach (var task in Model.Tasks)
{
<option value="@task.Id" data-employee="@task.EmployeeId"> @task.name </option>
}
</select>