我在更新第二个级联下拉列表时遇到问题,我希望能够从第一个下拉列表中选择一门课程,然后根据所选值使用课程部分列表填充第二个下拉列表。我有以下两个模型:
public class Course
{
[Key]
public int CourseID { get; set; }
public string CourseTitle { get; set; }
public virtual ICollection<CourseSection> CourseSections { get; set; }
}
public class CourseSection
{
[Key]
public int CourseSectionID { get; set; }
public int CourseID { get; set; }
public string Title { get; set; }
}
我对包含两个下拉列表的页面的视图如下:
<h3>Upload Course Section Content</h3>
<div class="row">
<div class="nine columns">
<label for="name">Select Course:</label>
<select id="coursedd" name="courseid" style="height:40px; font-size:18px;">
<option value="0" id ="defaultcid" class ="choosefilter" >----Please Select Course----</option>
@foreach (var course in Model.CourseList)
{
<option value="@course.CourseID" id ="courseid" class ="choosefilter" >@course.Name </option>
}
</select>
</div>
</div>
<div class="row" style="margin-top:30px;">
<div class="nine columns">
<label for="name" id="namelabel">Select Course Section:</label>
<select id="coursesectiondd" name="coursesectionid" style="height:40px; font-size:18px;">
<option value="0" id ="defaultcs" class ="choosefilter" >----Please Select Course Section----</option>
@if(Model.CourseSectionList != null)
{
foreach (var courseSection in Model.CourseSectionList)
{
<option value="@courseSection.CourseSectionID" id ="coursesectionid" class ="choosefilter" >@courseSection.Title </option>
}
}
else
{
}
</select>
</div>
</div>
如果课程下拉选择的值更改,则调用以下 jquery:
$(function () {
$("#coursedd").change(function () {
$('#namelabel').show();
$('#title').show();
$('#CourseSectionSubmit').show();
var chosen = document.getElementById("coursedd").value;
if (chosen == "0") {
$('#namelabel').hide();
$('#coursesectiondd').hide();
$('#file').hide();
$('#filelabel').hide();
}
else {
GetCourseID()
$.getJSON('@Url.Action("GetCourseID", "Admin")', { VendorGroup: DistributorID }, function (param) {
var courseSectionDropdown = $('#coursesectiondd');
courseSectionDropdown.empty();
$.each(param, function (index, param) {
courseSectionDropdown.append(
$('<option/>')
.attr('value', param.sectionID)
.text(param.sectionTitle)
);
});
});
}
});
});
在这个 jquery 的 else 上还有一个名为 GetCourseID() 的 javascript 方法,它具有以下代码:
function GetCourseID() {
var id = document.getElementById("coursedd").value;
var postData = {
'CourseID': id
};
$('#coursesectiondd').show();
$.post('/Admin/GetCourseID/', postData, function (data) {
document.getElementById("coursedd").selectedIndex = id;
});
};
链接到的控制器操作如下:
[HttpPost]
public ActionResult GetCourseID(int courseID)
{
IEnumerable<Course> Courses = avm.GetCourseList();
var Sections = dbcontext.CourseSection.Where(cs => cs.CourseID.Equals(courseID)).Select(x => new
{
sectionID = x.CourseSectionID,
sectionTitle = x.Title
});
return Json(Sections, JsonRequestBehavior.AllowGet);
}
有人可以帮我返回 Json 值并更新我的第二个下拉列表吗