"
ASP.NET (snapshot 2017) Microsoft documentation and samples

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.

[!code-cshtmlMain]

   1:  <table class="table">
   2:      <tr>
   3:          <th>
   4:              Course Title
   5:          </th>
   6:          <th>
   7:              Grade
   8:          </th>
   9:          <th>
  10:              Credits
  11:          </th>
  12:      </tr>
  13:   
  14:      @foreach (var item in Model.Enrollments)
  15:      {
  16:          <tr>
  17:              <td>
  18:                  @Html.DisplayFor(modelItem => item.Course.Title)
  19:              </td>
  20:              <td>
  21:                  @Html.DisplayFor(modelItem => item.Grade)
  22:              </td>
  23:              <td>
  24:                  @Html.DisplayFor(modelItem => item.Course.Credits)
  25:              </td>
  26:          </tr>
  27:      }
  28:  </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.

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
student with enrollment

Previous Next



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/mvc/overview/getting-started/database-first-development/customizing-a-view.htm
< THANKS ME>