Tutorial: Customize view for EF Database First with ASP.NET MVC app

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 tutorial focuses on changing the automatically-generated views to enhance the presentation.

In this tutorial, you:

  • Add courses to the student detail page
  • Confirm that the courses are added to the page

Prerequisites

Add courses to student detail

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 Views > Students > Details.cshtml. Below the last </dl> tag, 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. The Display method renders HTML for the object (modelItem) that represents the expression. You use the Display method (rather than simply embedding the property value in the code) to make sure the value is formatted correctly based on its type and the template for that type. In this example, each expression returns a single property from the current record in the loop, and the values are primitive types which are rendered as text.

Confirm courses are added

Run the solution. Click List of students and select Details for one of the students. You will see the enrolled courses have been included in the view.

student with enrollment

Next steps

In this tutorial, you:

  • Added courses to the student detail page
  • Confirmed that the courses are added to the page

Advance to the next tutorial to learn how to add data annotations to specify validation requirements and display formatting.