Contoso大学第5部分,无需传递参数即可读取相关数据

时间:2013-08-27 21:36:12

标签: asp.net-mvc entity-framework

我正在介绍Contoso大学ASP.NET MVC示例第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

当我选择教师讲授的课程时,我无法理解如何将id参数传递给控制器​​/视图。 在视图中,显示课程的部分如下:

@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> 

}

控制器索引功能如下:

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);
    }

为什么在**视图中,我不必传递id,如下所示:

@Html.ActionLink("Select", "Index", new { id= ViewBag.InstructorID,courseID = item.CourseID }) 

谢谢!

1 个答案:

答案 0 :(得分:0)

简短的回答是,这是一些Asp.net MVC神奇的工作。当您对从中解析视图的同一个Controller执行回发时,Razor视图引擎会保留任何先前传递的路由值。首次加载页面时,IdCourseId都没有值。第一次返回索引控制器(对于讲师)包括Id,并且Id将自动附加到此视图对索引控制器的所有调用。因此第二次调用时,您只需添加CourseId值,因为Id值已经附加到URL。如果值已更改,或者您要链接到其他Controller,则只需提供Id值。您可以通过手动检查Razor在第二个链接操作上生成的完整URL来验证这一点。