日期:2014-05-17 浏览次数:21654 次
In the previous tutorial you created an MVC application that stores and displays data using the Entity Framework and SQL Server Compact. In this tutorial you will review and customize the CRUD (create, read, update, delete) code that the MVC scaffolding automatically creates for you in controllers and views.
Note?? It's a common practice to implement the repository pattern in order to create an abstraction layer between your controller and the data access layer. To keep these tutorials simple, you won't implement a repository until a later tutorial in this series (Implementing the Repository and Unit of Work Patterns).
In this tutorial, you will create the following web pages:
The scaffolded code for the Index page left out the Enrollments
property, because that property holds a collection. In the Details page you will display the contents of the collection in an HTML table.
In Controllers\StudentController.cs, the action method for the Details view resembles the following example:
public ViewResult Details(int id) { Student student = db.Students.Find(id); return View(student); }
The code uses the Find
method to retrieve a single Student
entity corresponding to the key value that's passed to the method as the id
parameter. The id
value comes from a query string in the Details hyperlink on the Index page.
Open Views\Student\Details.cshtml. Each field is displayed using a DisplayFor
helper, as shown in the following example:
<div class="display-label">LastName</div> <div class="display-field"> @Html.DisplayFor(model => model.LastName) </div>
To display a list of enrollments, add the following code after the EnrollmentDate
field, immediately before the closing fieldset
tag:
<div class="display-label"> @Html.LabelFor(model => model.Enrollments) </div> <div class="display-field"> <table> <tr> <th>Course Title</th> <th>Grade</th> </tr> @foreach (var item in Model.Enrollments) { <tr> <td> @Html.DisplayFor(modelItem => item.Course.Title) </td> <td> @Html.DisplayFor(modelItem => item.Grade) </td> </tr> } </table> </div>
This code loops through the entities in the Enrollments
navigation property. For each Enrollment
entity in the property, it displays the course title and the gr