【发布时间】:2015-07-22 19:58:49
【问题描述】:
大家好,这是我在这里的第一篇文章,所以如果我说什么或做一些愚蠢的事情,请保持温和:P 这也是我在 ASP.NET 中的第一个真实项目,我确信我在代码中犯了一些错误。
我正在开发一个 ASP.NET MVC 5 Web 应用程序,该应用程序具有 3 个 DropDownLists,其中填充了来自数据库的字符串。这 3 个列表是学期、课程和顾问名称。我希望能够根据所做的选择动态更改 DropDownLists。
我目前所做的假设是首先选择学期,然后是课程,然后是顾问姓名。选择学期后,代码不会填充顾问姓名。
在我理解了我的错误之后,我还希望能够以任何顺序选择 3 个选项中的任何一个。
这是我的控制器
public ActionResult Index(string Semester1, string Course1, string Consultant1)
{
ViewBag.semester = new SelectList(db.StudentInfos.Select(x => x.semester).Distinct().OrderBy(x => x));
ViewBag.course = new SelectList(db.StudentInfos.Select(x => x.WCOnlineCourse) .Distinct().OrderBy(x => x));
ViewBag.consultant = new SelectList(db.StudentInfos.Select(x => x.consultant).Distinct().OrderBy(x => x));
if (Semester1 != null)
{
ViewBag.course = new SelectList(db.StudentInfos.Where(x => x.semester == Semester1).Select(x => x.WCOnlineCourse).Distinct().OrderBy(x => x));
ViewBag.consultant = new SelectList(db.StudentInfos.Where(x => x.semester == Semester1).Select(x => x.consultant).Distinct().OrderBy(x => x));
if (Course1 != null)
{
ViewBag.consultant = new SelectList(db.StudentInfos.Where(x => x.semester == Semester1).Where(x => x.WCOnlineCourse == Course1).Select(x => x.consultant).Distinct().OrderBy(x => x));
}
}
return View();
}
这是我的看法
@model IEnumerable<StudentSurvey.Models.StudentInfo>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<table class="table">
<tr>
<th>
Semester
</th>
<th>
Course
</th>
<th>
Consultant
</th>
</tr>
<tr>
@using (Html.BeginForm("Index", "StudentInfos", FormMethod.Post))
{
<td>
@Html.DropDownList("Semester1", (SelectList)ViewBag.semester, "Select Semester", new { onchange = "this.form.submit();" })
</td>
<td>
@Html.DropDownList("Course1", (SelectList)ViewBag.course, "Select Course", new { onchange = "this.form.submit();" })
</td>
<td>
@Html.DropDownList("Consultant1", (SelectList)ViewBag.consultant, "Select Consultant", new { onchange = "this.form.submit();" })
</td>
}
</tr>
</table>
【问题讨论】:
-
要填充您的级联下拉菜单,请参阅this answer。有关工作示例,请参阅this DotNetFiddle
标签: c# asp.net asp.net-mvc asp.net-mvc-4 asp.net-mvc-5