Tuesday, 27 August 2013

Contoso University part 5, reading related data without passing parameter

Contoso University part 5, reading related data without passing parameter

I am walking through Contoso University ASP.NET MVC example part 5.
http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/reading-related-data-with-the-entity-framework-in-an-asp-net-mvc-application
I can't quite understand how the id parameter was passed to the
controller/view when I select a course taught by the instructor. In the
view, the section to display the courses is as following:
@if (Model.Courses != null)
{
<h3>Courses Taught by Selected Instructor</h3>
<table>
<tr>
<th></th>
<th>ID</th>
<th>Title</th>
<th>Department</th>
</tr>
@foreach (var item in Model.Courses)
{
string selectedRow = "";
if (item.CourseID == ViewBag.CourseID)
{
selectedRow = "selectedrow";
}
<tr class="@selectedRow">
<td>
*@Html.ActionLink("Select", "Index", new { courseID =
item.CourseID })*
</td>
<td>
@item.CourseID
</td>
<td>
@item.Title
</td>
<td>
@item.Department.Name
</td>
</tr>
}
</table>
}
The Controller Index function is as following:
public ActionResult Index(int? id, int? courseID)
{
var viewModel = new InstructorIndexData();
viewModel.Instructors = db.Instructors.Include(r =>
r.OfficeAssignment)
.Include(r => r.Courses.Select(c => c.Department))
.OrderBy(i => i.LastName);
if (id != null)
{
ViewBag.InstructorID = id.Value;
viewModel.Courses = viewModel.Instructors.Where(
i => i.InstructorID == id.Value).Single().Courses;
}
if (courseID != null)
{
ViewBag.Courses = courseID.Value;
//eager loading
//viewModel.Enrollments = viewModel.Courses.Where(
// i => i.CourseID == courseID.Value).Single().Enrollments;
//equivalant, but explicit loading
var selectedCourse = viewModel.Courses.Where(x => x.CourseID
== courseID).Single();
db.Entry(selectedCourse).Collection(x => x.Enrollments).Load();
foreach (Enrollment enrollment in selectedCourse.Enrollments)
{
db.Entry(enrollment).Reference(x => x.Student).Load();
}
viewModel.Enrollments = selectedCourse.Enrollments;
}
return View(viewModel);
}
Why in the ** line of view, I don't have to pass id, as in the following:
@Html.ActionLink("Select", "Index", new { id=
ViewBag.InstructorID,courseID = item.CourseID })
Thanks!

No comments:

Post a Comment