MVC 4 根据 DropDownListFor 选择更改字段
首先,与上面的问题几乎相同,但解决方案不适用于这个问题。
我有一个包含下拉列表的页面。选择后,它将根据选择更改显示字段。
视图中的 javascript 是:
<script type="text/javascript">
$(function(){
$('#courseName').on('change', function () {
var courseID = $(this).val();
var studentID = '@ViewBag.StudentID';
$.ajax({
url: '@Url.Action("FillCourseInfo", "Student")',
data: {StudentID: studentID, CourseID: courseID},
type: 'get'
}).done(function(data){
$('#courseStartDate').text(data.courseStartDate);
$('#courseEndDate').text(data.courseEndDate);
$('#projectName').text(data.projectName);
$('#graduated').text(data.graduated);
});
});
});
</script>
风景:
<tr>
<th class="table-row">
Course Title:
</th>
<td class="table-row">
@Html.DropDownListFor(m => m.courseName,
@ViewBag.courseList as SelectList, " -- Select Course -- ",
new { @class = "form-control" })
</td>
</tr>
<tr>
<th class="table-row">
Start & End Date:
</th>
<td class="table-row">
<label id="#courseStartDate" class="form-control">@Model.courseStartDate</label>
</td>
<td class="table-row">
<label id="#courseEndDate" class="form-control">@Model.courseEndDate</label>
</td>
</tr>
<tr>
<th class="table-row">
Project:
</th>
<td class="table-row">
<label id="#projectName" class="form-control">@Model.projectName</label>
</td>
</tr>
<tr>
<th class="table-row">
Graduated:
</th>
<td class="table-row">
<label id="#graduated">@Model.graduated</label>
</td>
</tr>
和控制器方法:
[HttpGet]
public JsonResult FillCourseInfo(int StudentID, int CourseID)
{
var ret = (from e in db.Enrollments
join c in db.Courses on e.CourseID equals c.CourseID
where e.StudentID == StudentID && e.CourseID == CourseID
select new
{
courseStartDate = c.CourseStartDate,
courseEndDate = c.CourseEndDate,
projectName = e.Project.ProjectTitle,
graduated = e.Graduated
}).ToList()
.Select(a => new StudentCourseDetails() {
courseStartDate = a.courseStartDate.ToString("MMM d, yyyy"),
courseEndDate = a.courseEndDate.ToString("MMM d, yyyy"),
projectName = a.projectName,
graduated = a.graduated.Value.ToString()
}).FirstOrDefault();
string sd = ret.courseStartDate;
string ed = ret.courseEndDate;
string pn = ret.projectName;
string g = ret.graduated;
return Json(ret, JsonRequestBehavior.AllowGet);
}
目前,javascript 没有受到影响,或者我的方法没有被调用。