C# – Implement CRUD Functionality – ASP.NET MVC with EF Core – Video

This is the second video of the Microsoft tutorials, for ASP.NET MVC with Entity Framework Core:

C# - Implement CRUD Functionality - ASP.NET MVC with EF Core

Continuing the previous video, in this one the following tasks are carried out:

  • Customize the Details page
  • Update the Create page
  • Update the Edit page
  • Update the Delete page

The customization of the Details page was the most interesting part of the tutorial, thus allowing us to unite data from two tables – students and enrollments:

This is the Details.cshtml code:

@model ContosoUniversity.Models.Student

@{
    ViewData["Title"] = "Details";
}

<h2>Details</h2>

<div>
    <h4>Student</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.LastName)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.LastName)
        </dd>
        <dt>
            @Html.DisplayNameFor(model => model.FirstMidName)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.FirstMidName)
        </dd>
        <dt>
            @Html.DisplayNameFor(model => model.EnrollmentDate)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.EnrollmentDate)
        </dd>
        @*we write courses here!*@
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model=>model.Enrollments)
        </dt>
        <dd class="col-sm-10">
            <table class="table">
                <tr>
                    <th>Course Title</th>
                    <th>Grade</th>
                </tr>
                @foreach (var item in Model.Enrollments)
                {
                    <tr>
                        <td>
                            @Html.DisplayFor(modeltem => item.Course.Title)
                        </td>
                        <td>
                            @Html.DisplayFor(modelitem => item.Grade)
                        </td>
                    </tr>
                }
            </table>
        </dd>
    </dl>
</div>
<div>
    <a asp-action="Edit" asp-route-id="@Model.Id">Edit</a> |
    <a asp-action="Index">Back to List</a>
</div>

And the details controller:

        // GET: Students/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var student = await _context.Students
                .Include(s => s.Enrollments)
                .ThenInclude(e => e.Course)
                .AsNoTracking()
                .FirstOrDefaultAsync(m => m.Id == id);

            if (student == null)
            {
                return NotFound();
            }

            return View(student);
        }

For everything else, here is GitHub – https://github.com/Vitosh/ASP/tree/master/EFCoreAsp.NetMvcWebApp/ContosoUniversity002