我要添加多个级联下拉列表。我正在使用Code第一种方法和MVC 5 .NET框架。
的屏幕以下是模型:
public class CourseAssign
{
[Key]
public int Id { get; set; }
public int DepartmentId { get; set; }
public int TeacherId { get; set; }
public int CourseId { get; set; }
public bool Status { get; set; }
[ForeignKey("DepartmentId")]
public virtual Department Department { get; set; }
[ForeignKey("TeacherId")]
public virtual Teacher Teacher { get; set; }
[ForeignKey("CourseId")]
public virtual Course Course { get; set; }
}
现在我需要为部门选择加载教师和课程,而不是加载所有教师和课程。
Department Model properties are similar to **Department[Id, Code, Name]**
Teacher Model is like **Teacher[Id, Name, DepartmentId]**
Course Model is like **Course[Id, Code, Name, DepartmentId]**
在Controller类" CourseAssignsController" 我添加了以下代码:
public JsonResult GetTeachers(int DepartmentId)
{
var teachers = from a in db.Teachers where a.DepartmentId == DepartmentId select a;
return Json(teachers.ToArray(), JsonRequestBehavior.AllowGet);
}
表单或视图代码中的3个选择输入选项:
<div class="form-group">
@Html.LabelFor(model => model.DepartmentId, "Department", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("DepartmentId", null, "---------------- Select ----------------", htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.DepartmentId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.TeacherId, "Teacher", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("TeacherId", null, "---------------- Select ----------------", htmlAttributes: new { @class = "form-control" })
@*<select id="TeacherId"></select>*@
@*@Html.DropDownList("TeacherId", new SelectList(string.Empty, "Value", "Text"), "Please select a state", new { @style = "width:250px;" })*@
@Html.ValidationMessageFor(model => model.TeacherId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.CourseId, "Course Code", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("CourseId", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.CourseId, "", new { @class = "text-danger" })
</div>
</div>
视图中的脚本是:
<script>
$(function() {
$('#DepartmentId').change(function () {
var departmentId = $("#DepartmentId").val();
$('#TeacherId').empty();
var json = {
id: departmentId
};
$.ajax({
type: "POST",
url: '@Url.Action("GetTeachers", "CourseAssigns")',
contentType: "application/json; charset=utf-8",
datatype: "Json",
data: { countryId: $('#DepartmentId').val() },
success: function (data) {
$.each(data, function (index, value) {
$('#TeacherId').append('<option value="' + value.Id + '">' + value.Name + '</option>');
});
}
});
});
});
这一切都是我尝试从互联网搜索。但是我的编码条件无法正确应用。什么都不适用于部门选项的变化。