deyno7 deyno7 -4 years ago 75
C# Question

c# - How can I filter the table based on a dropdown selection in mvc application and then display the data?

I am doing my first ever mvc application and I am kind of stuck. What I'm trying to do is filter the existing table based on the selection from the dropdown list.
I have a Course table and a Teacher table and I'd like to be able to filter the Courses by who is teaching them.

This is my controller so far:

namespace TTimetable.Controllers
{
public class CoursesController : Controller
{
private TimetabledbEntities db = new TimetabledbEntities();

// GET: Courses
public ActionResult Index(int teacher)
{
ViewBag.Teacher = new SelectList(db.Teacher, "teacher_Id", "lastName");
var course = db.Course.Include(c => c.Classroom).Include(c => c.Teacher);
return View(course.ToList());
}


This is my View:

@model IEnumerable<TTimetable.Models.Course>

@{
ViewBag.Title = "Courses";
}

<h2>Courses</h2>

<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.name)
</th>
<th>
@Html.DisplayNameFor(model => model.course_start)
</th>
<th>
@Html.DisplayNameFor(model => model.course_end)
</th>
<th>
@Html.DisplayNameFor(model => model.Classroom.classroom_no)
</th>
<th>
teacher
</th>
</tr>

@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.name)
</td>
<td>
@Html.DisplayFor(modelItem => item.course_start)
</td>
<td>
@Html.DisplayFor(modelItem => item.course_end)
</td>
<td>
@Html.DisplayFor(modelItem => item.Classroom.classroom_no)
</td>
<td>
@Html.DisplayFor(modelItem => item.Teacher.firstName)
</td>
</tr>
}

</table>

<h2>Courses taught by:</h2>
@Html.DropDownList("Teacher", "Select teacher")


So far I was only able to make the dropdown list display the teachers from the database. Anyone who could help me with this? It'll be much appreciated. Thanks

Answer Source

You will need to have your dropdown list post back to the server. This can be accomplished by wrapping the dropdown in a form, and adding javascript to submit the form:

using (Html.BeginForm("Index", "Courses", FormMethod.Get))
{
    Html.DropDownList("Teacher", ViewBag.Teacher, "Select teacher", new { onchange = @"form.submit();" });
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download