Reputation: 9
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
Upvotes: 0
Views: 3496
Reputation: 304
here viewbag should be casted as it is dynamic type object.
@Html.DropDownList("Teacher", (SelectList)ViewBag.Teacher, "Select teacher", new { onchange = @"form.submit();" });
hope it helps for your solution.
Upvotes: 0
Reputation: 273
Suggest you to use to Odata approach , when you have multiple filters , for a single table . It will be easy for you in the future.
combining both the techniques can help you.
Upvotes: 0
Reputation: 539
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();" });
}
Upvotes: 1