无论您是否使用ASP.NET MVC,都可以使用jQuery 来实现。这是实现您需要的一种方式,您可能还可以遵循其他解决方案,但这对我有用。
以下是我的代码示例,您可以对其进行修改以适应您的场景。在我的示例中,我将在添加新用户时与部门和单位合作。一个部门由不同的单位组成。因此,当从第一个下拉列表中选择一个部门时,该部门的所有单位都将显示在第二个下拉列表中。
让我从视图(页面)开始。它接受一个名为CreateUserViewModel 的视图模型。应始终使用视图模型,而不是通过您的域模型。
@model MyProject.ViewModels.Users.CreateUserViewModel
代表我的两个下拉菜单的 HTML 标记:
<tr>
<td class="edit-label">Department <span class="required">*</span></td>
<td>
@Html.DropDownListFor(
x => x.DepartmentId,
new SelectList(Model.Departments, "Id", "Name", Model.DepartmentId),
"-- Select --",
new { id = "Departments" }
)
@Html.ValidationMessageFor(x => x.DepartmentId)
</td>
</tr>
<tr>
<td class="edit-label">Unit <span class="required">*</span></td>
<td>
@Html.DropDownListFor(
x => x.UnitId,
new SelectList(Model.Units, "Id", "Name", Model.UnitId),
"-- Select --",
new { id = "Units" }
)
@Html.ValidationMessageFor(x => x.UnitId)
</td>
</tr>
我的CreateUserViewModel 班级(部分):
public class CreateUserViewModel
{
public int DepartmentId { get; set; }
public IEnumerable<Department> Departments { get; set; }
public int UnitId { get; set; }
public IEnumerable<Unit> Units { get; set; }
}
我的Department班级:
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
}
我的Unit 班级:
public class Unit
{
public int Id { get; set; }
public string Name { get; set; }
public int DepartmentId { get; set; }
public virtual Department Department { get; set; }
}
第一次加载视图时,我填充了部门下拉列表,而单位下拉列表为空。
public ActionResult Create()
{
CreateUserViewModel viewModel = new CreateUserViewModel
{
Departments = departmentService.GetAll(),
Units = Enumerable.Empty<Unit>()
};
return View(viewModel);
}
回到我的视图(页面)我使用jQuery 填充我的第二个下拉列表:
<script>
function resetDropDown(targetDropDown) {
var items = '';
items = '<option>-- Select --</option>';
$(targetDropDown).empty();
$(targetDropDown).html(items);
}
$(document).ready(function () {
$("#Departments").change(function () {
var url = '@Url.Action("GetUnitsByDepartmentId", "User")';
var departmentId = $("#Departments").val();
if (departmentId == '') {
resetDropDown($('#Units'));
return;
}
$.getJSON(url, { departmentId: departmentId }, function (data) {
$('#Units').empty();
var items = '<option>-- Select --</option>';
$.each(data, function (i, unit) {
items += "<option value='" + unit.Id + "'>" + unit.Name + "</option>";
});
$('#Units').html(items);
});
});
});
</script>
在我的控制器中有一个操作方法可以将我的单位作为JSON 结果返回:
public ActionResult GetUnitsByDepartmentId(int departmentId)
{
IEnumerable<Unit> units = unitService.GetUnitsByDepartmentId(departmentId);
var displayedUnits = units.Select(x => new
{
Id = x.Id.ToString(),
Name = x.Name
});
return Json(displayedUnits, JsonRequestBehavior.AllowGet);
}
此解决方案可能并不完美,但它会引导您朝着正确的方向前进。一切顺利。