我在aspnet mvc中建立一个员工注册表,我在1个下拉框中有“学校”列表和“部门”列表另一个字段,问题是我想在学校列表的更改上显示部门列表,我已经完成了以下代码:
public ActionResult EmployeeCreate()
{
var getSchool = SchoolRepository.GetAllSchoolsInArray();//this gets school_id as value and school_name as text for dropdown box
ViewData["SchoolsList"] = getSchool;
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EmployeeCreate()
{
_employeeRepository.CreateEmployee(employeeToCreate);
_employeeRepository.SaveToDb();
}
这是视图
Html.DropDownList("SchoolLists")
Html.DropDownList("DepartmentLists")
现在,我如何在下拉框中找到所选学校的部门
答案 0 :(得分:1)
如果您希望在此值更改时根据所选学校的值填充“部门”列表,则可以使用javascript和AJAX。因此,您设置了一个控制器操作,该操作将返回给定学校的部门:
public DepartmentsController: Controller
{
public ActionResult Index(int? schoolId)
{
var departments = _depsRepo.GetDepartmentsForSchool(schoolId);
return Json(departments);
}
}
一旦你拥有了这个控制器,就可以使用jQuery来注册学校的变更事件:
$(function() {
$('#SchoolList').change(function() {
var schoolId = $(this).val();
$.getJSON('/departments/index', { schoolId: schoolId },
function(departments) {
var depsList = $('#DepartmentLists');
depsList.empty();
$(departments).each(function(i, department) {
// Id and Name used here should be properties
// of the department model
depsList.append(
'<option value="' + department.Id + '">' +
department.Name + '</option>'
);
});
});
});
});