Language

EF Database First with ASP.NET MVC: Customizing a View

By Tom FitzMacken|

Using MVC, Entity Framework, and ASP.NET Scaffolding, you can create a web application that provides an interface to an existing database. This tutorial series shows you how to automatically generate code that enables users to display, edit, create, and delete data that resides in a database table. The generated code corresponds to the columns in the database table.

This part of the series focuses on changing the automatically-generated views to enhance the presentation.

Add enrolled courses to student details

The generated code provides a good starting point for your application but it does not necessarily provide all of the functionality that you need in your application. You can customize the code to meet the particular requirements of your application. Currently, your application does not display the enrolled courses for the selected student. In this section, you will add the enrolled courses for each student to the Details view for the student.

Open Students/Details.cshtml, and below the last </dl> tab, but before the closing </div> tag, add the following code.

<table class="table">
    <tr>
        <th>
            Course Title
        </th>
        <th>
            Grade
        </th>
        <th>
            Credits
        </th>
    </tr>

    @foreach (var item in Model.Enrollments)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Course.Title)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Grade)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Course.Credits)
            </td>
        </tr>
    }
</table>

This code creates a table that displays a row for each record in the Enrollment table for the selected student. Browse to the Students/Index view again and select Details for one of the students. You will see the enrolled courses have been included in the view.

student with enrollment

This article was originally created on October 30, 2013

Author Information

Tom FitzMacken

Tom FitzMacken – Tom FitzMacken is a Senior Programming Writer on the Web Platform & Tools Content team.