Note that all columns have NOT NULL attribute unchecked so they cannot contain NULL in them.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Mvc;
-
- namespace CRUDEF.Controllers
- {
- public class HomeController : Controller
- {
- public IActionResult Index()
- {
- return View();
- }
- }
- }
In this controller I will perform the CRUD operation on the ‘Teacher’s’ table. So I will need the ‘StudentContext’ service injected to it using Dependency Injection feature. So update this controller as shown below:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using CRUDEF.Models;
- using Microsoft.AspNetCore.Mvc;
-
- namespace CRUDEF.Controllers
- {
- public class HomeController : Controller
- {
- private SchoolContext schoolContext;
- public HomeController(SchoolContext sc)
- {
- schoolContext = sc;
- }
-
- public IActionResult Index()
- {
- return View();
- }
- }
- }
Adding Client Side Validation feature
The Client Side validation feature is performed by ‘jQuery’ and 2 validation plugins,
- jQuery Validation
- jQuery Validation Unobtrusive
To install these 3 run the following commands in the ‘Package Manager Console’ window,
- 1. PM> Install-Package jQuery -Version 3.3.1
- 2. PM> Install-Package jQuery.Validation -Version 1.17.0
- 3. PM> Install-Package jQuery.Validation.Unobtrusive -Version 2.0.20710
Performing the CREATE Teacher Functionality
The CREATE Teacher Functionality is done through a new Action method called ‘CREATE’. Add this action method to the ‘Home Controller’. It is shown in the below code,
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using CRUDEF.Models;
- using Microsoft.AspNetCore.Mvc;
-
- namespace CRUDEF.Controllers
- {
- public class HomeController : Controller
- {
- private SchoolContext schoolContext;
- public HomeController(SchoolContext sc)
- {
- schoolContext = sc;
- }
-
- public IActionResult Index()
- {
- return View();
- }
-
- public IActionResult Create()
- {
- return View();
- }
-
- [HttpPost]
- public IActionResult Create(Teacher teacher)
- {
- if (ModelState.IsValid)
- {
- schoolContext.Teacher.Add(teacher);
- schoolContext.SaveChanges();
- return RedirectToAction("Index");
- }
- else
- return View();
- }
- }
- }
The [HttpPost] version of the Create action creates a new teacher in the database. It uses Entity Framework Core to create the record. Notice the below 2 lines of code with actually does the insert of the record into the database,
- schoolContext.Teacher.Add(teacher);
- schoolContext.SaveChanges();
Next, add the ‘Views’ folder in the root of the application. Inside this folder create a new folder called ‘Home’.
Next, create a new View called ‘Create.cshtml’ inside this ‘Home’ folder (i.e. ‘Views>Home’). Add the following code to this View,
- @model Teacher
-
- @{
- Layout = "_Layout";
- var title = "CREATE Teacher";
- ViewData["Title"] = title;
- }
-
- <style>
- .input-validation-error {
- border-color: red;
- }
- </style>
-
- <h2>@title</h2>
-
- <div asp-validation-summary="ModelOnly" class="text-danger"></div>
- <form class="m-1 p-1" method="post">
- <div class="form-group">
- <label asp-for="Name"></label>
- <input asp-for="Name" class="form-control" />
- <span asp-validation-for="Name" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="Skills"></label>
- <input asp-for="Skills" type="text" class="form-control" />
- <span asp-validation-for="Skills" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="TotalStudents"></label>
- <input asp-for="TotalStudents" type="text" class="form-control" />
- <span asp-validation-for="TotalStudents" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="Salary"></label>
- <input asp-for="Salary" type="text" class="form-control" />
- <span asp-validation-for="Salary" class="text-danger"></span>
- </div>
- <button type="submit" class="btn btn-primary">Submit</button>
- </form>
-
- <script src="/lib/jquery/dist/jquery.min.js"></script>
- <script src="/lib/jquery-validation/dist/jquery.validate.min.js"></script>
- <script src="/lib/jquery-validation-unobtrusive/dist/jquery.validate.unobtrusive.min.js"></script>
The View has a Model of type ‘Teacher’ and it creates Input fields for ‘Name, Skills, TotalStudents and Salary’, so that user can fill and submit it.
When the Submit button is clicked then the Create Action of type HttpPost, is called and the new teacher records is created.
Notice the 3 script files which do the Client Side Validation of the input fields in the View,
- <script src="/lib/jquery/dist/jquery.min.js"></script>
- <script src="/lib/jquery-validation/dist/jquery.validate.min.js"></script>
- <script src="/lib/jquery-validation-unobtrusive/dist/jquery.validate.unobtrusive.min.js"></script>
Testing the Create Teacher functionality
Run the application and in the browser go to the URL of ‘Create’ View, which is – http://localhost:52730/Home/Create. You will see the Create Teacher form in the browser.
Without filling any fields press the Submit button and you will see the validation errors displayed by jQuery Validation plugins.
Now fill all the fields (as shown by the below image) and click the submit button.
The teacher record will be created in the database and you will be redirected to the Index View which is currently empty.
You can confirm the record is inserted in the Teacher’s table. For this go to the ‘SQL Server Object Explorer’, then right click the ‘Teacher’ table and select ‘View Data’.
The teacher table will open and you will see the new teacher record in it, see the below image:
Performing the READ Teacher Functionality
Now we will create the READ Teacher Functionality. So change the Index Action in the Home Controller to return all the teachers to the View as shown below:
- public IActionResult Index()
- {
- return View(schoolContext.Teacher);
- }
The code – 'schoolContext.Teacher' will get all the teachers entity from Entity Framework Core.
Next, add the ‘Index’ View inside the ‘Views/Home/’ folder with the following code,
- @model IEnumerable<Teacher>
-
- @{
- Layout = "_Layout";
- var title = "READ Teacher";
- ViewData["Title"] = title;
- }
-
- <h2>@title</h2>
-
- <h3><a asp-action="Create" class="btn btn-sm btn-secondary">Create</a></h3>
- <table class="table table-bordered table-sm table-striped">
- <thead>
- <tr><th>Id</th><th>Name</th><th>Skills</th><th>Total Students</th><th>Salary</th><th>Added On</th><th>Update</th><th>Delete</th></tr>
- </thead>
- <tbody>
- @if (Model == null)
- {
- <tr><td colspan="7" class="text-center">No Model Data</td></tr>
- }
- else
- {
- @foreach (var p in Model)
- {
- <tr>
- <td>@p.Id</td>
- <td>@p.Name</td>
- <td>@p.Skills</td>
- <td>@p.TotalStudents</td>
- <td>@string.Format(new System.Globalization.CultureInfo("en-US"), "{0:C2}", p.Salary)</td>
- <td>@string.Format("{0:dddd, dd MMMM yyyy}", p.AddedOn)</td>
- <td><a asp-action="Update" asp-route-id="@p.Id">Update</a></td>
- <td>
- <form asp-action="Delete" method="post" asp-route-id="@p.Id">
- <button>Delete</button>
- </form>
- </td>
- </tr>
- }
- }
- </tbody>
- </table>
Notice that I have also created the columns for Update and Delete functionality in the table’s thread and body elements,
- <table class="table table-bordered table-sm table-striped">
- <thead>
- <tr><th>Id</th><th>Name</th><th>Skills</th><th>Total Students</th><th>Salary</th><th>Added On</th><th>Update</th><th>Delete</th></tr>
- </thead>
- <tbody>
- …
- else
- {
- @foreach (var p in Model)
- {
- <tr>
- …
- <td><a asp-action="Update" asp-route-id="@p.Id">Update</a></td>
- <td>
- <form asp-action="Delete" method="post" asp-route-id="@p.Id">
- <button>Delete</button>
- </form>
- </td>
- </tr>
- }
- }
- </tbody>
- </table>
We will create the Update and Delete Functionality in the next sections.
Testing the Read Teacher functionality
Run your application and you will see the Teacher’s table records get displayed in the Index View. This is shown by the below image,
Performing the UPDATE Teacher functionality
Add the 2 Update Actions to the Home Controller as shown below:
- public IActionResult Update(int id)
- {
- return View(schoolContext.Teacher.Where(a => a.Id == id).FirstOrDefault());
- }
-
- [HttpPost]
- [ActionName("Update")]
- public IActionResult Update_Post(Teacher teacher)
- {
- schoolContext.Teacher.Update(teacher);
- schoolContext.SaveChanges();
- return RedirectToAction("Index");
- }
The HttpGet version of Update action method takes the ‘id’ of the Teacher records in its parameter and fetches the record from the database using EF Core like,
- schoolContext.Teacher.Where(a => a.Id == id).FirstOrDefault());
The HttpPost version of Update action method takes the Teacher class in it’s parameter which is bound with updated values from the Update View. The Updated values are saved in the database table by EF core like this,
- schoolContext.Teacher.Update(teacher);
- schoolContext.SaveChanges();
Next, create the Update View inside the ‘Views/Home/’ folder with the following code,
- @model Teacher
-
- @{
- Layout = "_Layout";
- var title = "UPDATE Teacher";
- ViewData["Title"] = title;
- }
-
- <style>
- .input-validation-error {
- border-color: red;
- }
- </style>
-
- <h2>@title</h2>
-
- <div asp-validation-summary="ModelOnly" class="text-danger"></div>
- <form class="m-1 p-1" method="post">
- <div class="form-group">
- <label asp-for="Id"></label>
- <input asp-for="Id" type="text" readonly class="form-control" />
- </div>
- <div class="form-group">
- <label asp-for="Name"></label>
- <input asp-for="Name" type="text" class="form-control" />
- <span asp-validation-for="Name" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="Skills"></label>
- <input asp-for="Skills" type="text" class="form-control" />
- <span asp-validation-for="Skills" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="TotalStudents"></label>
- <input asp-for="TotalStudents" type="text" class="form-control" />
- <span asp-validation-for="TotalStudents" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="Salary"></label>
- <input asp-for="Salary" type="text" class="form-control"/>
- <span asp-validation-for="Salary" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="AddedOn"></label>
- <input asp-for="AddedOn" type="text" class="form-control" asp-format="{0:d}" />
- </div>
- <button type="submit" class="btn btn-primary">Submit</button>
- </form>
-
- <script src="/lib/jquery/dist/jquery.min.js"></script>
- <script src="/lib/jquery-validation/dist/jquery.validate.min.js"></script>
- <script src="/lib/jquery-validation-unobtrusive/dist/jquery.validate.unobtrusive.min.js"></script>
The View is similar to the Index View we created earlier. I have made the ‘Id’ field as readonly so that user cannot change it.
Testing the Update Teacher functionality
Run your application and click the ‘Update’ link for the 1st teacher records, see below image,
The record will open for updation. Change name to ‘Bill Gates’ and salary to ‘100000000’. Finally click the submit button as shown by the below image,
Record will be updated and you will be redirected to the Index View where you can see the updated record fields as shown by the below image,
Performing the DELETE Teacher Functionality
Create Delete Action method in the Home Controller whose code is given below:
- [HttpPost]
- public IActionResult Delete(int id)
- {
- var teacher = schoolContext.Teacher.Where(a => a.Id == id).FirstOrDefault();
- schoolContext.Teacher.Remove(teacher);
- schoolContext.SaveChanges();
- return RedirectToAction("Index");
- }
This method takes the id of the teacher’s record in its parameter and fetches that record from the database table using the below EF Core code:
- var teacher = schoolContext.Teacher.Where(a => a.Id == id).FirstOrDefault();
Finally it deletes that record from the database table like:
- schoolContext.Teacher.Remove(teacher);
- schoolContext.SaveChanges();
Testing the Delete Teacher functionality
Run your application and click the ‘Delete’ link given against any of the record. Check the below images which shows the record deletion process,
Conclusion
This completes this CRUD operations tutorial in ASP.NET Core and Entity Framework core. I hope you loved reading this and now understand how the codes are working. If you have any confusion go through all the Source Codes which you can download from this tutorial itself.
Please like and share this tutorial on your Facebook and Twitter accounts and let your friends learn ASP.NET Core. It hardly takes a few seconds of your time.
Thank you!